memindex 1.5.0 → 1.7.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 (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +15 -12
  3. package/.codex-plugin/plugin.json +17 -14
  4. package/.qoder-plugin/plugin.json +1 -1
  5. package/README.md +89 -110
  6. package/THIRD_PARTY_LICENSES +7 -0
  7. package/dist/bug-report/index.js +54 -54
  8. package/dist/npx-cli/index.js +451 -443
  9. package/dist/opencode-plugin/index.js +33 -33
  10. package/integrations/dsh/package.json +1 -1
  11. package/integrations/openclaw/openclaw.plugin.json +1 -1
  12. package/package.json +15 -12
  13. package/plugin/.claude-plugin/plugin.json +15 -12
  14. package/plugin/.codex-plugin/plugin.json +15 -12
  15. package/plugin/.qoder-plugin/plugin.json +1 -1
  16. package/plugin/hooks/codex-hooks.json +14 -14
  17. package/plugin/hooks/hooks.json +8 -8
  18. package/plugin/hooks.json +4 -4
  19. package/plugin/package.json +1 -1
  20. package/plugin/plugin.json +1 -1
  21. package/plugin/scripts/context-generator.cjs +55 -54
  22. package/plugin/scripts/context-generator.cjs.map +2 -2
  23. package/plugin/scripts/hook-runner.cjs +248 -0
  24. package/plugin/scripts/hook-runner.cjs.map +6 -0
  25. package/plugin/scripts/mcp-server.cjs +99 -89
  26. package/plugin/scripts/mcp-server.cjs.map +2 -2
  27. package/plugin/scripts/qoder-hook-launcher.cjs +1 -1
  28. package/plugin/scripts/transcript-watcher.cjs +32 -32
  29. package/plugin/scripts/transcript-watcher.cjs.map +2 -2
  30. package/plugin/scripts/windows-hook-launcher.cjs +2 -2
  31. package/plugin/scripts/worker-service.cjs +655 -641
  32. package/plugin/scripts/worker-service.cjs.map +3 -3
  33. package/plugin/sqlite/SessionStore.js +90 -89
  34. package/plugin/sqlite/SessionStore.js.map +3 -3
  35. package/plugin/sqlite/observations/files.js +12 -12
  36. package/plugin/sqlite/observations/files.js.map +2 -2
  37. package/plugin/ui/assets/fonts/dm-sans-OFL.txt +93 -0
  38. package/plugin/ui/assets/fonts/dm-sans-latin.woff2 +0 -0
  39. package/plugin/ui/assets/fonts/ibm-plex-mono-OFL.txt +93 -0
  40. package/plugin/ui/assets/fonts/ibm-plex-mono-latin.woff2 +0 -0
  41. package/plugin/ui/assets/fonts/manrope-OFL.txt +93 -0
  42. package/plugin/ui/assets/fonts/manrope-latin.woff2 +0 -0
  43. package/plugin/ui/viewer-bundle.js +14 -14
  44. package/plugin/ui/viewer.html +450 -321
@@ -1,50 +1,50 @@
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 _b=Object.create;var Pa=Object.defineProperty;var Eb=Object.getOwnPropertyDescriptor;var Sb=Object.getOwnPropertyNames;var yb=Object.getPrototypeOf,bb=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 Us=(t,e)=>{for(var r in e)Pa(t,r,{get:e[r],enumerable:!0})},wb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Sb(e))!bb.call(t,s)&&s!==r&&Pa(t,s,{get:()=>e[s],enumerable:!(n=Eb(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?_b(yb(t)):{},wb(e||!t||!t.__esModule?Pa(r,"default",{value:t,enumerable:!0}):r,t));function ka(t){return t.startsWith($s)||Bs.some(e=>t.startsWith(e))}function Ib(t=process.env){for(let e of Bs)for(let r of Object.keys(t)){if(!r.startsWith(e))continue;let n=$s+r.slice(e.length);t[n]===void 0&&(t[n]=t[r])}}function Ws(t){let e=null;for(let r of Bs)for(let n of Object.keys(t)){if(!n.startsWith(r))continue;let s=$s+n.slice(r.length);(e??t)[s]===void 0&&(e??={...t},e[s]=t[n])}return e??t}var $s,Tb,Bs,cn=E(()=>{"use strict";$s="MEMINDEX_",Tb="AGENT_MEM_",Bs=[Tb];Ib()});function Ee(t,e=process.platform,r=(0,$d.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 $d,Bd,qt=E(()=>{"use strict";$d=require("os"),Bd=require("path")});function Rb(t){return(vb??process.stderr.write.bind(process.stderr))(t)}function mt(t){Rb(t)}var vb,Q0,js=E(()=>{"use strict";vb=null;Q0=Promise.resolve()});function Mb(t,e,r=C.renameSync,n=Hd){for(let s=0;;s++)try{r(t,e);return}catch(o){if(!n||s>=Wd.length||!Ab.has(o.code??""))throw o;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Wd[s])}}function xa(t){return t.replace(/^\uFEFF/,"")}function Jt(t){return JSON.parse(xa(t))}function ht(t){return Jt((0,C.readFileSync)(t,"utf-8"))}function Ob(t){(0,C.existsSync)(t)||(0,C.mkdirSync)(t,{recursive:!0})}function $(t,e,r={}){Pb(t,JSON.stringify(e,null,2)+`
5
- `,r)}function Pb(t,e,r={}){let n=t,s=new Set;try{for(;(0,C.lstatSync)(n).isSymbolicLink();){let d=(0,$e.resolve)(n);if(s.has(d))throw Object.assign(new Error(`Symlink loop at ${n}`),{code:"ELOOP"});s.add(d);try{n=(0,C.realpathSync)(n);break}catch(p){if(p.code!=="ENOENT")throw p;let g=p instanceof Error?p:new Error(String(p));mt(`memindex: realpathSync failed for ${n}, resolving symlink manually: ${g.message}
6
- `);let m=(0,C.readlinkSync)(n);n=(0,$e.resolve)((0,$e.dirname)(n),m)}}}catch(d){if(d.code!=="ENOENT")throw d}Ob((0,$e.dirname)(n));let o=(0,$e.dirname)(n),i=(0,$e.basename)(n),a=(0,$e.join)(o,`.${i}.${process.pid}.${(0,jd.randomBytes)(6).toString("hex")}.tmp`),c=Buffer.from(e,"utf-8"),u=r.mode;if(u===void 0)try{u=(0,C.statSync)(n).mode&511}catch{}let l;try{l=u!==void 0?(0,C.openSync)(a,"w",u):(0,C.openSync)(a,"w");let d=0;for(;d<c.length;){let p=(0,C.writeSync)(l,c,d,c.length-d);if(p===0)throw new Error(`writeSync stalled at ${d}/${c.length} bytes`);d+=p}if((0,C.fsyncSync)(l),(0,C.closeSync)(l),l=void 0,Mb(a,n),!Hd){let p;try{p=(0,C.openSync)(o,"r"),(0,C.fsyncSync)(p)}catch(g){let m=g instanceof Error?g:new Error(String(g));mt(`memindex: directory fsync failed for ${o}: ${m.message}
7
- `)}finally{if(p!==void 0)try{(0,C.closeSync)(p)}catch{}}}}catch(d){if(l!==void 0)try{(0,C.closeSync)(l)}catch{}try{(0,C.unlinkSync)(a)}catch{}throw d}}var C,jd,$e,Hd,Ab,Wd,oe=E(()=>{"use strict";C=require("fs"),jd=require("crypto"),$e=require("path");js();Hd=process.platform==="win32",Ab=new Set(["EPERM","EBUSY","EACCES"]),Wd=[10,20,40,80,160,320]});function Xd(t){let e=t.env;return kb(e)&&Object.keys(e).some(ka)?"nested":"flat"}function br(t){return Xd(t)==="nested"?t.env:t}function Kd(t){return Xd(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!ka(e)))}var kb,Hs=E(()=>{"use strict";oe();cn();kb=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function un(t=process.env,e=(0,zd.homedir)()){if(t.MEMINDEX_DATA_DIR)return Ee(t.MEMINDEX_DATA_DIR,process.platform,e);let r=(0,Na.join)(e,".memindex"),n=(0,Na.join)(r,"settings.json");try{if((0,Gd.existsSync)(n)){let s=ht(n);if(s===null||typeof s!="object"||Array.isArray(s))return r;let o=Ws(br(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 Gd,zd,Na,Ca=E(()=>{"use strict";Gd=require("fs"),zd=require("os"),Na=require("path");oe();cn();qt();Hs()});function xb(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,j.dirname)((0,Vd.fileURLToPath)(Lb.url))}function Nb(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 x(){return Nb(un())}function Yd(){return process.env.MEMINDEX_DEV_HOOK_SOURCE==="1"}function Jd(t,e=(0,Da.homedir)(),r=process.platform){return Ee(t,r,e)}var j,Da,Vd,Lb,gx,W,Cb,Be,wr,Db,V,qd,mx,Xs,Fb,B,N=E(()=>{"use strict";j=require("path"),Da=require("os"),Vd=require("url");qt();Ca();qt();Lb={};gx=xb();W=x(),Cb=(0,j.join)((0,Da.homedir)(),".claude"),Be=process.env.CLAUDE_CONFIG_DIR||Cb,wr=(0,j.join)(Be,"plugins","marketplaces","memindex");Db=(0,j.join)(W,"logs"),V=(0,j.join)(W,"settings.json"),qd="memindex.db",mx=(0,j.join)(W,qd),Xs=(0,j.join)(W,"observer-sessions"),Fb=(0,j.basename)(Xs);B={dataDir:()=>W,workerPid:()=>(0,j.join)(W,"worker.pid"),workerHeartbeat:()=>(0,j.join)(W,"worker-heartbeat.json"),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,qd),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:()=>Db}});function Qd(t=process.env){let e=Number.parseInt(t.MEMINDEX_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=Zd.min&&e<=Zd.max?e:Ub}function $b(t=process.platform){return t==="win32"?8e3:5e3}function ln(t=process.platform){return ie.SESSION_INIT_HOOK_CAP-$b(t)}function ef(t=process.platform){return t==="win32"?ln(t):ie.SESSION_INIT_REQUEST_MAX}function Rt(t){return process.platform==="win32"?Math.round(t*ie.WINDOWS_MULTIPLIER):t}var ie,Ub,Zd,D,rt=E(()=>{"use strict";ie={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},Ub=300,Zd={min:60,max:86400};D={SUCCESS:0}});function Ks(t){return new RegExp(`${t}${Bb}`,"gi")}function Xb(t,e){let r=0;e.lastIndex=0;for(let n of t.matchAll(e))r=n.index+n[0].length;return r}function Gs(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>jb)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Hb,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,...Wb];for(let a of i){if(r.has(a.name))continue;let c=a.endMarker?Xb(s,a.endMarker):s.length;c!==0&&(a.regex.lastIndex=0,s=s.slice(0,c).replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`))+s.slice(c))}return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function Kb(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 nf(t){return{enabled:t.MEMINDEX_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.MEMINDEX_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:Kb(t.MEMINDEX_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.MEMINDEX_REDACT_LOG_MATCHES==="true"}}function Vb(t){if(!(0,pn.existsSync)(t))return null;try{return(0,pn.readFileSync)(t,"utf-8")}catch{return""}}function Yb(t){if(t===null)return!1;try{let e=JSON.parse(xa(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function qb(t,e,r){return process.env.MEMINDEX_REDACT_ENABLED==="false"||!(fn?.enabled===!0||zb.test(e))?r:(rf||(rf=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:fn?.enabled?"the last configuration that loaded":"the built-in patterns"})),fn?.enabled?fn:sf)}function La(t=V){let e=Date.now();if(dn&&e-tf<Gb)return dn;let r=Tr;Tr=!0;try{let n=F.loadFromFile(t),s=nf(n),o=s.enabled?null:Vb(t);return Yb(o)?dn=qb(t,o,s):(dn=s,fn=s),tf=e,dn}finally{Tr=r}}function of(t){let e=Gs(t,sf).redacted;if(Tr)return e;Tr=!0;try{let r=(0,pn.existsSync)(V)?La():nf(process.env);return Gs(e,{...r,logMatches:!1}).redacted}finally{Tr=!1}}var pn,Fa,Bb,Wb,jb,Hb,dn,tf,Gb,fn,rf,Tr,sf,zb,Ua=E(()=>{"use strict";pn=require("fs");M();Ie();N();oe();Fa=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,Bb=`(?=${Fa}{8})${Fa}*[A-Za-z]${Fa}*`;Wb=[{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,endMarker:/-----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:Ks(String.raw`(?<=\b\w*_?(?:password|passwd|pwd)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"generic_token",regex:Ks(String.raw`(?<=\b\w*_(?:token|secret|api_key)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"bearer_token",regex:Ks(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:Ks(String.raw`(?<=\b(?:token|secret|api[_-]?key|apikey)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)}],jb=1024*1024,Hb="<redacted type='oversize'/>";dn=null,tf=0,Gb=5e3,fn=null,rf=!1,Tr=!1,sf={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},zb=/"(?:MEMINDEX|AGENT_MEM)_REDACT_ENABLED"\s*:\s*"true"/});var ve,af,Ba,$a,Wa,f,M=E(()=>{"use strict";ve=require("fs"),af=require("path");N();js();oe();Hs();Ua();Ba=(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))(Ba||{}),$a=null,Wa=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=B.logsDir();(0,ve.mkdirSync)(B.dataDir(),{recursive:!0,mode:448}),(0,ve.chmodSync)(B.dataDir(),448),(0,ve.mkdirSync)(n,{recursive:!0,mode:448}),(0,ve.chmodSync)(n,448),this.logFilePath=(0,af.join)(n,`memindex-${e}.log`),(0,ve.appendFileSync)(this.logFilePath,"",{mode:384}),(0,ve.chmodSync)(this.logFilePath,384),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=B.settings();if((0,ve.existsSync)(e)){let r=br(ht(e)),n=(r.MEMINDEX_LOG_LEVEL||r.AGENT_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=Ba[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 Sb=Object.create;var Pa=Object.defineProperty;var yb=Object.getOwnPropertyDescriptor;var bb=Object.getOwnPropertyNames;var wb=Object.getPrototypeOf,Tb=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 Ls=(t,e)=>{for(var r in e)Pa(t,r,{get:e[r],enumerable:!0})},Ib=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bb(e))!Tb.call(t,s)&&s!==r&&Pa(t,s,{get:()=>e[s],enumerable:!(n=yb(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?Sb(wb(t)):{},Ib(e||!t||!t.__esModule?Pa(r,"default",{value:t,enumerable:!0}):r,t));function ka(t){return t.startsWith(Us)||$s.some(e=>t.startsWith(e))}function Rb(t=process.env){for(let e of $s)for(let r of Object.keys(t)){if(!r.startsWith(e))continue;let n=Us+r.slice(e.length);t[n]===void 0&&(t[n]=t[r])}}function Bs(t){let e=null;for(let r of $s)for(let n of Object.keys(t)){if(!n.startsWith(r))continue;let s=Us+n.slice(r.length);(e??t)[s]===void 0&&(e??={...t},e[s]=t[n])}return e??t}var Us,vb,$s,cn=E(()=>{"use strict";Us="MEMINDEX_",vb="AGENT_MEM_",$s=[vb];Rb()});function Ee(t,e=process.platform,r=(0,$d.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 $d,Bd,qt=E(()=>{"use strict";$d=require("os"),Bd=require("path")});function Mb(t){return(Ab??process.stderr.write.bind(process.stderr))(t)}function mt(t){Mb(t)}var Ab,Q0,Ws=E(()=>{"use strict";Ab=null;Q0=Promise.resolve()});function Pb(t,e,r=C.renameSync,n=jd){for(let s=0;;s++)try{r(t,e);return}catch(o){if(!n||s>=Wd.length||!Ob.has(o.code??""))throw o;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Wd[s])}}function xa(t){return t.replace(/^\uFEFF/,"")}function Jt(t){return JSON.parse(xa(t))}function ht(t){return Jt((0,C.readFileSync)(t,"utf-8"))}function kb(t){(0,C.existsSync)(t)||(0,C.mkdirSync)(t,{recursive:!0})}function $(t,e,r={}){xb(t,JSON.stringify(e,null,2)+`
5
+ `,r)}function xb(t,e,r={}){let n=t,s=new Set;try{for(;(0,C.lstatSync)(n).isSymbolicLink();){let d=(0,$e.resolve)(n);if(s.has(d))throw Object.assign(new Error(`Symlink loop at ${n}`),{code:"ELOOP"});s.add(d);try{n=(0,C.realpathSync)(n);break}catch(p){if(p.code!=="ENOENT")throw p;let g=p instanceof Error?p:new Error(String(p));mt(`memindex: realpathSync failed for ${n}, resolving symlink manually: ${g.message}
6
+ `);let m=(0,C.readlinkSync)(n);n=(0,$e.resolve)((0,$e.dirname)(n),m)}}}catch(d){if(d.code!=="ENOENT")throw d}kb((0,$e.dirname)(n));let o=(0,$e.dirname)(n),i=(0,$e.basename)(n),a=(0,$e.join)(o,`.${i}.${process.pid}.${(0,Hd.randomBytes)(6).toString("hex")}.tmp`),c=Buffer.from(e,"utf-8"),u=r.mode;if(u===void 0)try{u=(0,C.statSync)(n).mode&511}catch{}let l;try{l=u!==void 0?(0,C.openSync)(a,"w",u):(0,C.openSync)(a,"w");let d=0;for(;d<c.length;){let p=(0,C.writeSync)(l,c,d,c.length-d);if(p===0)throw new Error(`writeSync stalled at ${d}/${c.length} bytes`);d+=p}if((0,C.fsyncSync)(l),(0,C.closeSync)(l),l=void 0,Pb(a,n),!jd){let p;try{p=(0,C.openSync)(o,"r"),(0,C.fsyncSync)(p)}catch(g){let m=g instanceof Error?g:new Error(String(g));mt(`memindex: directory fsync failed for ${o}: ${m.message}
7
+ `)}finally{if(p!==void 0)try{(0,C.closeSync)(p)}catch{}}}}catch(d){if(l!==void 0)try{(0,C.closeSync)(l)}catch{}try{(0,C.unlinkSync)(a)}catch{}throw d}}var C,Hd,$e,jd,Ob,Wd,oe=E(()=>{"use strict";C=require("fs"),Hd=require("crypto"),$e=require("path");Ws();jd=process.platform==="win32",Ob=new Set(["EPERM","EBUSY","EACCES"]),Wd=[10,20,40,80,160,320]});function Xd(t){let e=t.env;return Nb(e)&&Object.keys(e).some(ka)?"nested":"flat"}function br(t){return Xd(t)==="nested"?t.env:t}function Kd(t){return Xd(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!ka(e)))}var Nb,Hs=E(()=>{"use strict";oe();cn();Nb=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function un(t=process.env,e=(0,zd.homedir)()){if(t.MEMINDEX_DATA_DIR)return Ee(t.MEMINDEX_DATA_DIR,process.platform,e);let r=(0,Na.join)(e,".memindex"),n=(0,Na.join)(r,"settings.json");try{if((0,Gd.existsSync)(n)){let s=ht(n);if(s===null||typeof s!="object"||Array.isArray(s))return r;let o=Bs(br(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 Gd,zd,Na,Ca=E(()=>{"use strict";Gd=require("fs"),zd=require("os"),Na=require("path");oe();cn();qt();Hs()});function Cb(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,H.dirname)((0,Vd.fileURLToPath)($b.url))}function Db(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 x(){return Db(un())}function Yd(){return process.env.MEMINDEX_DEV_HOOK_SOURCE==="1"}function Jd(t,e=(0,Da.homedir)(),r=process.platform){return Ee(t,r,e)}var H,Da,Vd,$b,gx,W,Fb,Be,wr,Lb,V,qd,mx,js,Ub,B,N=E(()=>{"use strict";H=require("path"),Da=require("os"),Vd=require("url");qt();Ca();qt();$b={};gx=Cb();W=x(),Fb=(0,H.join)((0,Da.homedir)(),".claude"),Be=process.env.CLAUDE_CONFIG_DIR||Fb,wr=(0,H.join)(Be,"plugins","marketplaces","memindex");Lb=(0,H.join)(W,"logs"),V=(0,H.join)(W,"settings.json"),qd="memindex.db",mx=(0,H.join)(W,qd),js=(0,H.join)(W,"observer-sessions"),Ub=(0,H.basename)(js);B={dataDir:()=>W,workerPid:()=>(0,H.join)(W,"worker.pid"),workerHeartbeat:()=>(0,H.join)(W,"worker-heartbeat.json"),serverPid:()=>(0,H.join)(W,".server-beta.pid"),serverPort:()=>(0,H.join)(W,".server-beta.port"),serverRuntime:()=>(0,H.join)(W,".server-beta.runtime.json"),settings:()=>(0,H.join)(W,"settings.json"),database:()=>(0,H.join)(W,qd),chroma:()=>(0,H.join)(W,"chroma"),combinedCerts:()=>(0,H.join)(W,"combined_certs.pem"),transcriptsConfig:()=>(0,H.join)(W,"transcript-watch.json"),transcriptsState:()=>(0,H.join)(W,"transcript-watch-state.json"),corpora:()=>(0,H.join)(W,"corpora"),supervisorRegistry:()=>(0,H.join)(W,"supervisor.json"),envFile:()=>(0,H.join)(W,".env"),logsDir:()=>Lb}});function Qd(t=process.env){let e=Number.parseInt(t.MEMINDEX_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=Zd.min&&e<=Zd.max?e:Bb}function Wb(t=process.platform){return t==="win32"?8e3:5e3}function ln(t=process.platform){return ie.SESSION_INIT_HOOK_CAP-Wb(t)}function ef(t=process.platform){return t==="win32"?ln(t):ie.SESSION_INIT_REQUEST_MAX}function Rt(t){return process.platform==="win32"?Math.round(t*ie.WINDOWS_MULTIPLIER):t}var ie,Bb,Zd,D,rt=E(()=>{"use strict";ie={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},Bb=300,Zd={min:60,max:86400};D={SUCCESS:0}});function Xs(t){return new RegExp(`${t}${Hb}`,"gi")}function jb(t){let e=String.raw`(?:(?<=\\[nrt])|\b)`,r=t.regex.source.replace(/(^|\||\(\?:|\(\?<=)\\b/g,`$1${e}`);return{...t,regex:new RegExp(r,t.regex.flags)}}function Gb(t,e){let r=0;e.lastIndex=0;for(let n of t.matchAll(e))r=n.index+n[0].length;return r}function Gs(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>Xb)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Kb,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},s=t;if(!r.has("cookie")&&/cookie/i.test(t)){let a=!1;try{JSON.parse(t),a=!0}catch{}if(a){let c="<redacted type='cookie'/>",u=tf[0].regex,l=()=>(n.cookie=(n.cookie??0)+1,c),d=[],p=!1;s=t.replace(/"(?:\\.|[^"\\])*"|[{}\[\],]/g,(g,m)=>{if(g==="{"||g==="[")return d.push(g==="["&&(p||d.at(-1)===!0)),p=!1,g;if((g==="}"||g==="]")&&d.pop(),g===","||g==="}"||g==="]")return p=!1,g;let h=JSON.parse(g);if(/^\s*:/.test(t.slice(m+g.length)))return p=/^(?:set-)?cookie$/i.test(h),g;let _=p||d.at(-1)===!0;if(p=!1,_&&h.length>=4)return h===c?g:'"'+l()+'"';u.lastIndex=0;let S=[...h.matchAll(u)];if(S.length===0)return g;let b=[];for(let v=1;v<g.length-1;)b.push(v),v+=g[v]==="\\"?g[v+1]==="u"?6:2:1;b.push(g.length-1);let w=g;for(let v of S.reverse()){let I=b[v.index],y=b[v.index+v[0].length];w=w.slice(0,I)+l()+w.slice(y)}return w})}}let 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,...tf];for(let a of i){if(r.has(a.name))continue;let c=a.endMarker?Gb(s,a.endMarker):s.length;c!==0&&(a.regex.lastIndex=0,s=s.slice(0,c).replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`))+s.slice(c))}return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function zb(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 sf(t){return{enabled:(t.MEMINDEX_REDACT_ENABLED??F.get("MEMINDEX_REDACT_ENABLED"))==="true",disabledBuiltinPatterns:(t.MEMINDEX_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:zb(t.MEMINDEX_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.MEMINDEX_REDACT_LOG_MATCHES==="true"}}function Yb(t){if(!(0,fn.existsSync)(t))return null;try{return(0,fn.readFileSync)(t,"utf-8")}catch{return""}}function qb(t){if(t===null)return!1;try{let e=JSON.parse(xa(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function Jb(t,e){return process.env.MEMINDEX_REDACT_ENABLED==="false"?e:(nf||(nf=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:Ks?.enabled?"the last configuration that loaded":"the built-in patterns"})),Ks?.enabled?Ks:of)}function La(t=V){let e=Date.now();if(dn&&e-rf<Vb)return dn;let r=Tr;Tr=!0;try{let n=F.loadFromFile(t),s=sf(n),o=Yb(t);return qb(o)?dn=Jb(t,s):(dn=s,Ks=s),rf=e,dn}finally{Tr=r}}function af(t){let e=Gs(t,of).redacted;if(Tr)return e;Tr=!0;try{let r=(0,fn.existsSync)(V)?La():sf(process.env);return Gs(e,{...r,logMatches:!1}).redacted}finally{Tr=!1}}var fn,Fa,Hb,tf,Xb,Kb,dn,rf,Vb,Ks,nf,Tr,of,Ua=E(()=>{"use strict";fn=require("fs");M();Ie();N();oe();Fa=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,Hb=`(?=${Fa}{8})${Fa}*[A-Za-z]${Fa}*`;tf=[{name:"cookie",regex:/(?<=(?:^|[\r\n])[ \t]*(?:[<>][ \t]*)?(?:set-)?cookie[ \t]*:[ \t]*)(?![ \t])[^\r\n<]{4,}|(?<='(?:set-)?cookie[ \t]*:[ \t]*)(?![ \t])[^'\r\n<]{4,}|(?<="(?:set-)?cookie[ \t]*:[ \t]*)(?![ \t])(?:\\.|[^"\\\r\n<]){4,}|(?<=\b(?:set-)?cookie\\{0,2}["']?\s*:\s*\\{0,2}["']?)(?![ \t])[^\\\r\n"'`<]{4,}/gi},{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,endMarker:/-----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:"atlassian_token",regex:/\bATATT3[A-Za-z0-9_=-]{186}(?![\w=-])/g},{name:"heroku_token",regex:/\bHRKU-AA[A-Za-z0-9_-]{58}(?![\w-])/g},{name:"grafana_token",regex:/\b(?:glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8}(?!\w)|glc_[A-Za-z0-9+/]{32,400}={0,2}(?![\w+/=]))/g},{name:"postman_token",regex:/\bPMAK-[a-f0-9]{24}-[a-f0-9]{34}(?!\w)/g},{name:"pulumi_token",regex:/\bpul-[a-f0-9]{40}(?!\w)/g},{name:"doppler_token",regex:/\bdp\.(?:pt|st|ct)\.[A-Za-z0-9_-]{43,}(?![\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:Xs(String.raw`(?<=\b\w*_?(?:password|passwd|pwd)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"generic_token",regex:Xs(String.raw`(?<=\b\w*_(?:token|secret|api_key)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"bearer_token",regex:Xs(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:Xs(String.raw`(?<=\b(?:token|secret|api[_-]?key|apikey)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)}].map(jb),Xb=1024*1024,Kb="<redacted type='oversize'/>";dn=null,rf=0,Vb=5e3,Ks=null,nf=!1,Tr=!1,of={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1}});var ve,cf,Ba,$a,Wa,f,M=E(()=>{"use strict";ve=require("fs"),cf=require("path");N();Ws();oe();Hs();Ua();Ba=(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))(Ba||{}),$a=null,Wa=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=B.logsDir();(0,ve.mkdirSync)(B.dataDir(),{recursive:!0,mode:448}),(0,ve.chmodSync)(B.dataDir(),448),(0,ve.mkdirSync)(n,{recursive:!0,mode:448}),(0,ve.chmodSync)(n,448),this.logFilePath=(0,cf.join)(n,`memindex-${e}.log`),(0,ve.appendFileSync)(this.logFilePath,"",{mode:384}),(0,ve.chmodSync)(this.logFilePath,384),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=B.settings();if((0,ve.existsSync)(e)){let r=br(ht(e)),n=(r.MEMINDEX_LOG_LEVEL||r.AGENT_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=Ba[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=Ba[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(([w,T])=>typeof T!="object"||T===null||T instanceof Error||T instanceof Date?`${w}=${T}`:`${w}=${Array.isArray(T)?this.safeStringify(T):this.formatData(T)}`).join(", ")}}`)}let p=of(`[${i}] [${a}] [${c}] ${u}${n}${d}${l}`);if(this.logFilePath)try{(0,ve.appendFileSync)(this.logFilePath,p+`
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=af(`[${i}] [${a}] [${c}] ${u}${n}${d}${l}`);if(this.logFilePath)try{(0,ve.appendFileSync)(this.logFilePath,p+`
12
12
  `,{encoding:"utf8",mode:384})}catch(g){let m=g instanceof Error?g:new Error(String(g));mt(`[LOGGER] Failed to write to log file: ${m.message}
13
13
  ${m.stack??""}
14
14
  `)}else mt(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){$a=e}error(e,r,n,s){this.log(3,e,r,n,s),this.routeErrorToSink(r,n,s)}routeErrorToSink(e,r,n){try{if(!$a||!(n instanceof Error))return;$a(n)}catch{}}dataIn(e,r,n,s){this.info(e,`\u2192 ${r}`,n,s)}dataOut(e,r,n,s){this.info(e,`\u2190 ${r}`,n,s)}success(e,r,n,s){this.info(e,`\u2713 ${r}`,n,s)}failure(e,r,n,s){this.error(e,`\u2717 ${r}`,n,s)}},f=new Wa});function cf(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var uf=E(()=>{"use strict";M()});function Zt(t){let e=(0,Se.resolve)(t),r=[],n=e;for(;;)try{return(0,Se.join)(lf.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 ew(t,e){return Zt(t)===Zt(e)}function tw(t,e){let r=Zt(e);return t===r||t.startsWith(r.endsWith(Se.sep)?r:r+Se.sep)}function rw(t,e=(0,_t.homedir)()){let r=Zt(t),n=Zt(e);return(process.platform==="win32"?[(0,_t.tmpdir)()]:[(0,_t.tmpdir)(),...Qb]).some(o=>Zt(o)!==n&&tw(r,o))}function gn(t=process.env,e=(0,_t.homedir)()){return t.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:rw(un(t,e),e)}function pf(t){return(0,ja.createHash)("sha256").update(Se.win32.resolve(t).toLowerCase()).digest().readUInt32BE(0)%nw}function Ha(t=process.platform,e=(0,_t.homedir)()){return t==="win32"?ff+pf(e):38700+(process.getuid?.()??77)%100}function Xa(t=process.platform,e=(0,_t.homedir)()){return t==="win32"?ff+sw+pf(e):38877+(process.getuid?.()??77)%100}function Ka(t){let e=(0,ja.createHash)("sha256").update(Zt(t)).digest();return Jb+e.readUInt32BE(0)%Zb}function gf(t=process.env,e=(0,_t.homedir)()){return gn(t,e)?Ka(un(t,e)):Ha(process.platform,e)}function mf(t,e){return typeof t!="string"||t.length===0?"unknown":ew(t,e)?"same":"foreign"}var ja,lf,_t,Se,Jb,Zb,Qb,df,ff,nw,sw,Ga=E(()=>{"use strict";ja=require("crypto"),lf=require("fs"),_t=require("os"),Se=require("path");Ca();Jb=4e4,Zb=9e3,Qb=["/tmp","/private/tmp","/var/folders","/private/var/folders"],df="60";ff=39e3,nw=500,sw=500});function iw(t){return typeof t=="boolean"?String(t):t}function aw(t){let e=t.MEMINDEX_OPENROUTER_MODEL;if(typeof e!="string"||!ow.has(e.trim()))return!1;let r=typeof t.MEMINDEX_OPENROUTER_BASE_URL=="string"?t.MEMINDEX_OPENROUTER_BASE_URL.trim():"";return r===""||cf(r)}function Sf(t,e){return(0,At.join)((0,At.dirname)(t),`.${(0,At.basename)(t)}.${e.markerTag}`)}function za(t,e){try{(0,Qt.writeFileSync)(Sf(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Qt,At,mn,ow,hf,_f,Ef,F,Ie=E(()=>{"use strict";Qt=require("fs"),At=require("path"),mn=require("os");rt();oe();uf();cn();Hs();Ga();ow=new Set(["xiaomi/mimo-v2-flash:free"]);hf=18e4,_f=[{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"}];Ef=new Set,F=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_CONTEXT_PROJECTS:"current",MEMINDEX_WORKER_PORT:String(gf()),MEMINDEX_WORKER_HOST:"127.0.0.1",MEMINDEX_WORKER_HEARTBEAT_STALE_MS:"120000",MEMINDEX_ALLOWED_ORIGINS:"",MEMINDEX_PUBLIC_URL:"",MEMINDEX_API_TIMEOUT_MS:String(Rt(ie.API_REQUEST)),MEMINDEX_SESSION_INIT_TIMEOUT_MS:String(ln()),MEMINDEX_IDLE_EXIT_SEC:gn()?df:"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,At.join)((0,mn.homedir)(),".memindex"),MEMINDEX_SNAPSHOT_ENABLED:"true",MEMINDEX_SNAPSHOT_INTERVAL_HOURS:"24",MEMINDEX_SNAPSHOT_KEEP:"7",MEMINDEX_LOG_LEVEL:"INFO",MEMINDEX_LOG_RETENTION_DAYS:"30",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_BRANCH_ACTIVE_DAYS:"14",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,At.join)((0,mn.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,mn.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(hf),MEMINDEX_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS:String(hf),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(Xa())}`,MEMINDEX_SERVER_API_KEY:"",MEMINDEX_SERVER_PROJECT_ID:"",MEMINDEX_SERVER_BETA_URL:`http://127.0.0.1:${process.env.MEMINDEX_SERVER_PORT??String(Xa())}`,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,Qt.existsSync)(e)){let p=this.getAllDefaults();if(!n.readOnly)try{$(e,p,{mode:384});for(let g of _f)za(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,Qt.readFileSync)(e,"utf-8"),o=Jt(s),i=br(o),a=i!==o,c=Ws(i),u=Kd(o),l=a&&Object.keys(u).some(p=>p!=="env");if(a&&!l&&!n.readOnly)try{$(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(aw(c)){let p=String(c.MEMINDEX_OPENROUTER_MODEL).trim();if(c={...c,MEMINDEX_OPENROUTER_MODEL:this.DEFAULTS.MEMINDEX_OPENROUTER_MODEL},!n.readOnly)try{$(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 _f)if(!(0,Qt.existsSync)(Sf(e,p))){if(c[p.key]!==p.legacy){n.readOnly||za(e,p);continue}if(c={...c,[p.key]:this.DEFAULTS[p.key]},!n.readOnly)try{$(e,l?{...u,env:c}:c,{mode:384}),za(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}`;Ef.has(m)||(Ef.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]=iw(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 kf(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Ja,qs=E(()=>{"use strict";Ja="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 Zs(t=x()){let e=(0,H.openSync)((0,Js.join)(t,Nf),H.constants.O_RDONLY|(H.constants.O_NOFOLLOW??0));try{let r=(0,H.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,H.readFileSync)(e,"utf8");if(!hw.test(n))throw new Error("Invalid worker secret");return n}finally{(0,H.closeSync)(e)}}function Df(t=x()){(0,H.mkdirSync)(t,{recursive:!0,mode:448});let e=(0,Js.join)(t,Nf);try{return Zs(t)}catch(s){if(s.code!=="ENOENT")throw s}let r=(0,Js.join)(t,`.worker-secret-${(0,Mt.randomBytes)(16).toString("hex")}`),n=(0,H.openSync)(r,"wx",384);try{(0,H.fchmodSync)(n,384),(0,H.writeFileSync)(n,(0,Mt.randomBytes)(32).toString("hex")),(0,H.fsyncSync)(n)}finally{(0,H.closeSync)(n)}try{try{(0,H.linkSync)(r,e)}catch(s){if(s.code!=="EEXIST")throw s}}finally{(0,H.unlinkSync)(r)}return Zs(t)}function En(t,e=x()){let r=(t.method??"GET").toUpperCase(),n=r==="GET"||r==="HEAD",s=new Headers(t.headers);if(n)try{s.set(xf,Zs(e))}catch{return t}else s.set(xf,Df(e));return{...t,headers:s,redirect:"error"}}function Za(){return(0,Mt.randomBytes)(32).toString("hex")}function yw(t){return typeof t=="string"&&Cf.test(t)}function bw(t,e){return(0,Mt.createHmac)("sha256",t).update(_w+e).digest("hex")}function Qa(t,e,r=x()){if(typeof t!="string"||!Cf.test(t)||!yw(e))return!1;let n;try{n=Zs(r)}catch{return!1}let s=Buffer.from(bw(n,e)),o=Buffer.from(t);return o.length===s.length&&(0,Mt.timingSafeEqual)(o,s)}function Ff(t){try{return new URL(t).origin}catch{return null}}function tc(t,e=x(),r=Date.now()){let n=Ff(t);n!==null&&ec.set(n,{dataDir:e,at:r})}function Lf(){ec.clear()}function ww(t,e=x(),r=Date.now()){let n=Ff(t),s=n===null?void 0:ec.get(n);return s!==void 0&&s.dataDir===e&&r-s.at<Sw}function rc(t,e){let r=new URL("/api/health",t);return r.searchParams.set(Ew,e),r.toString()}async function Qs(t,e={}){let r=e.dataDir??x();if(!e.fresh&&ww(t,r))return!0;let n=Za(),o=await(e.fetchImpl??((c,u)=>fetch(c,u)))(rc(t,n),{method:"GET",redirect:"error",signal:e.signal?AbortSignal.any([e.signal,AbortSignal.timeout(Math.max(1,e.timeoutMs??2e3))]):AbortSignal.timeout(Math.max(1,e.timeoutMs??2e3))}),i=null;try{i=await o.json()}catch{}let a=typeof i=="object"&&i!==null?i.proof:void 0;return Qa(a,n,r)?(tc(t,r),!0):!1}var Mt,H,Js,xf,Nf,hw,Cf,_w,Ew,Sw,Rr,ec,nc=E(()=>{"use strict";Mt=require("node:crypto"),H=require("node:fs"),Js=require("node:path");N();qs();xf="X-Memindex-Secret",Nf="worker-secret",hw=/^[a-f0-9]{64}$/,Cf=/^[a-f0-9]{64}$/,_w="memindex-worker-identity:",Ew="challenge",Sw=1e3,Rr=class extends Error{constructor(e){super(e),this.name="WorkerIdentityError"}};ec=new Map});async function*Iw(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 vw(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*Bf(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 sc(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]===Tw)return e.onActivity?.(),null;p(m.length),a+=m.length;let h=n.decode(m),_=h.indexOf(":"),S=_===-1?h:h.slice(0,_),w=_===-1?"":h.slice(_+1);return w.startsWith(" ")&&(w=w.slice(1)),S==="event"?c=w:S==="data"?(l??=[]).push(w):S==="id"&&(u=w),null};for await(let m of Iw(t)){let h=0;for(let _=0;_<m.length;_++){let S=m[_];if(i&&(i=!1,S===$f)){h=_+1;continue}if(S!==Uf&&S!==$f)continue;s.push(m.subarray(h,_));let w=vw(s,o+(_-h));s=[],o=0;let T=g(w);T&&(e.terminalEventNames?.includes(T.event)&&(d=!0),yield T),i=S===Uf,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 oc(e.terminalEventNames)}var sc,oc,Uf,$f,Tw,Wf=E(()=>{"use strict";sc=class extends Error{constructor(r){super(`SSE event exceeded ${r} bytes`);this.maxEventBytes=r;this.name="SseEventTooLargeError"}maxEventBytes},oc=class extends Error{constructor(r){super(`SSE stream ended before a terminal event (${r.join(", ")})`);this.terminalEventNames=r;this.name="StreamEndedEarlyError"}terminalEventNames},Uf=13,$f=10,Tw=58});function z(){return eo!==null||(eo=F.loadFromFile(V)),eo}var eo,st=E(()=>{"use strict";Ie();N();eo=null});function to(t){return(t.MEMINDEX_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var jf=E(()=>{"use strict"});var Hf=E(()=>{"use strict"});function ic(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var ac=E(()=>{"use strict"});function uc(t,e,r){return(0,cc.spawn)(t,e??[],{...r,windowsHide:!0})}var cc,Rw,Aw,oN,lc=E(()=>{"use strict";cc=require("node:child_process");Rw=new Set([".cmd",".bat"]),Aw=new Set([".exe",".com"]),oN=new Set([...Aw,...Rw])});function je(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(kw.has(r)){e[r]=n;continue}Ow.has(r)||Mw.some(s=>r.startsWith(s))||(e[r]=n)}return e}var Mw,Ow,Pw,kw,Sn=E(()=>{"use strict";Mw=["CLAUDECODE_","CLAUDE_CODE_"],Ow=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Pw=new Set(["NODE_USE_ENV_PROXY","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"]),kw=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",...Pw])});function no(t){return`${dc}${t}`}function pc(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 Nw(t){fc+=1;let e=(0,ro.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:{...je(process.env),LC_ALL:"C",LANG:"C",TZ:"UTC"}});return pc("powershell-cim",t,e)}function Cw(t,e=!1){if(!e){let n=Xf.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<xw))return n.token}let r=null;try{r=Nw(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)&&Xf.set(t,{token:r,capturedAtMs:Date.now()}),r}function Gf(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){fc+=1;try{let r=(0,Kf.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 Cw(t,e);fc+=1;try{let r=(0,ro.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...je(process.env),LC_ALL:"C",LANG:"C",TZ:"UTC"}}),n=pc("ps-lstart",t,r);return n===null?null:no(n)}catch(r){return f.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Et(t){return Gf(t,!1)}function Dw(t,e){let r=Gf(t,!0);if(r===null||!r.startsWith(dc)||e.startsWith(dc))return r;try{let n=(0,ro.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...je(process.env),LC_ALL:"C",LANG:"C"}});return pc("ps-lstart",t,n)}catch{return null}}function Re(t,e){if(e===null)return!0;let r=Dw(t,e);return r===null?!0:r===e}var ro,Kf,dc,xw,Xf,fc,so=E(()=>{"use strict";ro=require("child_process"),Kf=require("fs");M();Sn();dc="utc:";xw=5e3,Xf=new Map,fc=0});async function Ae(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Et(t),s=()=>Re(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 gc("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===Fw||Lw.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new oo(t,`taskkill failed for PID ${t} (exit ${String(i)}): ${a.trim()||c}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",i=await io(t);for(let u of i){if(!Re(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 io(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(!Re(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 oo(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function Uw(){return process.platform==="win32"?Ww():process.platform==="linux"?$w():Bw()}function $w(){let t=[],e;try{e=(0,ao.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,ao.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 Bw(){let t;try{t=(await gc("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C",TZ:"UTC"}})).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?no(s):null})}return e}async function Ww(){let t;try{t=(await gc("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 io(t){let e=await Uw(),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 zf,ao,Vf,gc,Fw,Lw,oo,Ar=E(()=>{"use strict";zf=require("child_process"),ao=require("fs"),Vf=require("util");M();so();gc=(0,Vf.promisify)(zf.execFile),Fw=128,Lw=/not found|no running instance|no tasks/i,oo=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 co(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 qf(t){if(!t||!q(t.pid))return!1;if(!t.startToken)return!0;let e=Re(t.pid,t.startToken);return e||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken}),e}function uo(t,e=zw){if(!qf(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=>Yf.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 ot(t=B.workerPid()){if(!(0,tr.existsSync)(t))return null;let e;try{e=JSON.parse((0,tr.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&uo(e)?e:null}function lo(){return mc||(mc=new _c),mc}function hc(){let t=Vw.shift();t&&t.notify()}var tr,Yf,Hw,Xw,Kw,Gw,zw,_c,mc,vN,Vw,it=E(()=>{"use strict";lc();tr=require("fs"),Yf=_e(require("path"),1);M();oe();Sn();N();so();Ar();Hw=5e3,Xw=1e3,Kw=B.supervisorRegistry(),Gw=null;zw={platform:process.platform,readCommandLine:t=>(0,tr.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};_c=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Kw){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,tr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,tr.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"&&hc())}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)hc();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,Et(a.pid)]));for(let a of s)try{process.platform==="win32"?await Ae(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 co(s,Hw);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(!Re(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 Ae(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()+Xw;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"&&hc();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{$(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{Gw?.({errorCategory:r.code??"unknown"})}catch{}}},mc=null;vN=180*1e3,Vw=[]});async function Zf(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Yw,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,Et(c.pid)),o.set(c.id,await io(c.pid));try{await Jf(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 co(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=Re(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 Jf(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{qw(o.get(c.id)??[],c.pid)}}await co(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);Qf(r,e),t.registry.pruneDeadEntries()}function Qf(t,e,r=!1){if(!(0,Mr.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,Mr.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,Mr.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 qw(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!q(r))){if(!Re(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 Jf(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 Ae(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await Ae(r)}var Mr,Yw,Ec=E(()=>{"use strict";Mr=require("fs");M();it();N();Ar();Yw=B.workerPid()});function Jw(){let e=lo().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tp(){Or===null&&(Or=setInterval(Jw,ep),Or.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:ep}))}function rp(){Or!==null&&(clearInterval(Or),Or=null,f.debug("SYSTEM","Health checker stopped"))}var ep,Or,np=E(()=>{"use strict";M();it();ep=3e4,Or=null});function eT(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 tT(){let t=await Zw("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return eT(t.stdout)}function rT(t,e){let r=t.filter(i=>Qw.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 ip(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??tT,s=t.isAlive??q,o=t.killTree??(g=>Ae(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}=rT(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 w=m[S];_.status==="fulfilled"?(r.killed+=1,d.add(w.pid)):(r.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:w.pid,ppid:w.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 sp,op,Zw,Qw,ap=E(()=>{"use strict";sp=require("child_process"),op=require("util");M();Ar();it();Zw=(0,op.promisify)(sp.execFile),Qw=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function cp(t={}){let e=t.pidFilePath??nT;if(!(0,rr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,rr.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,rr.rmSync)(e,{force:!0}),"invalid"}return uo(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,rr.rmSync)(e,{force:!0})),"stale")}var rr,nT,Sc,KN,yn=E(()=>{"use strict";rr=require("fs");M();it();Ec();np();ap();N();it();nT=B.workerPid(),Sc=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(),cp({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ip({registry:this.registry}).catch(r=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),tp()}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}rp(),this.stopPromise=Zf({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}},KN=new Sc(lo())});function up(t,e){if(!(0,fo.existsSync)(t))return e;try{return Jt((0,fo.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var fo,lp=E(()=>{"use strict";fo=require("fs");oe()});function sT(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function oT(t,e){if(sT(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 go(t,e){return oT(t,e).enabled}function pp(t){let e=t.MEMINDEX_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function iT(){return(0,yc.join)(x(),fp)}function bn(){let t;try{t=up(iT(),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 aT(t){let e=x();(0,po.mkdirSync)(e,{recursive:!0}),(0,po.writeFileSync)((0,yc.join)(e,fp),JSON.stringify(t,null,2)+`
19
- `)}function mo(){let t=bn();if(t?.installId)return t.installId;let e=(0,dp.randomUUID)();return aT({installId:e,decidedAt:""}),e}var yc,po,dp,fp,bc=E(()=>{"use strict";yc=require("path"),po=require("fs"),dp=require("crypto");N();lp();M();fp="telemetry.json"});function _p(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>mp?e.slice(0,mp):e}catch{return""}}function wc(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=hp.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 Tc(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 cT(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${Me}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Me}@`))}function uT(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function lT(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)}${Me}`})}function dT(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,Me),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Me),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Me),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Me),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Me),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Me),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,Me),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Me),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,Me),e}function fT(t){return typeof t!="string"||t.length===0?t??"":t.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
20
- `).trim()}function Ic(t){let e=_p(t);return e.length===0?"":(e=wc(e),e=cT(e),e=Tc(e),e=uT(e),e=lT(e),e=dT(e),e)}function Ep(t){try{let e=fT(Ic(_p(t)));return e.length>gp?e.slice(0,gp):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 Sp(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 hp,gp,mp,Me,vc=E(()=>{"use strict";hp=_e(require("os"),1);M();gp=500,mp=8192,Me="[REDACTED]"});function gT(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!pT.has(r))continue;let n=t[r];if(typeof n=="string"){let s=n.length>yp?n.slice(0,yp):n;e[r]=Ic(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function ho(t){let e={};try{gT(t,e)}catch{}return e}var pT,yp,Rc=E(()=>{"use strict";vc();pT=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"]),yp=200});function _o(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function Eo(){return process.env.MEMINDEX_TELEMETRY_HOST||hT}function So(t){let e={};for(let r of _T)t[r]!==void 0&&(e[r]=t[r]);return e}function ET(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Ac.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 yo(){return{version:mT,os:process.platform,os_version:Ac.default.release(),is_wsl:ET(),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 Ac,mT,hT,_T,Mc=E(()=>{"use strict";Ac=_e(require("os"),1);M();mT="1.5.0",hT="https://us.i.posthog.com";_T=["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 bp(t,e,r){try{if(!go(process.env,bn()))return;let n=ho({...yo(),...e??{}});if(r?.person?n.$set=So(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=_o(),o=new AbortController,i=setTimeout(()=>o.abort(),ST);try{await yT(s,t,n,o.signal)}finally{clearTimeout(i)}}catch{}}async function yT(t,e,r,n){await fetch(`${Eo()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:mo(),properties:r}),signal:n})}var ST,wp=E(()=>{"use strict";bc();Rc();Mc();ST=2e3});var Tp=E(()=>{"use strict";M()});var Ip=E(()=>{"use strict";M();Tp()});function wn(t){return t.error?.name==="ETIMEDOUT"}function Tn(t,e,r=vp){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,bo.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})}})}).catch(o=>({status:null,stdout:"",error:o instanceof Error?o:new Error(String(o))}))}function In(t,e,r=vp){let n=(0,bo.spawnSync)("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,bT),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 bo,vp,bT,wo=E(()=>{"use strict";bo=require("child_process");M();vp=5e3,bT=5e3});function Rp(t){let e=Ot.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)}),vn}if(!r.isFile())return vn;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)}),vn}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return vn;let o=Ot.default.resolve(Ot.default.dirname(e),s[1]),i=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Ot.default.basename(t),parentRepoPath:c,parentProjectName:Ot.default.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Ot.default.basename(t),parentRepoPath:c,parentProjectName:Ot.default.basename(c)}}return vn}var To,Ot,vn,Ap=E(()=>{"use strict";To=require("fs"),Ot=_e(require("path"),1);M();vn={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Mp(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 Pc(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,Oc.basename)(r);for(let s of e){let o=s.trim();if(o)try{let i=Mp(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 Rn(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,Oc.basename)(r),s=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of s)try{let i=Mp(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 Oc,An=E(()=>{"use strict";Oc=require("path");qt();M()});function Pp(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 wT(t){try{return(0,Op.realpathSync)(t)}catch{return t}}function kc(t,e){if(e.length===0)return null;let r=[...new Set([t,wT(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(s=>Pc(s,n.patterns)))return n.name;return null}var Op,kp=E(()=>{"use strict";Op=require("fs");An();M()});function Cp(t){let e=process.env[TT]?.trim();return e||(!t||t.trim()===""?null:t)}function Dp(t){return Fp(t,In(t,["rev-parse","--show-toplevel"]))}async function RT(t){let e=Date.now(),r=Pr.get(t);if(r&&e-r.at<IT)return(await r.answer).root;Pr.size>=vT&&Pr.clear();let n=Tn(t,["rev-parse","--show-toplevel"]).then(a=>({root:Fp(t,a),kept:!wn(a)})),s={at:e,answer:n};Pr.set(t,s);let{root:o,kept:i}=await n;return!i&&Pr.get(t)===s&&Pr.delete(t),o}function Fp(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 Lp(t){try{return(0,xr.realpathSync)(t)}catch{return t}}function OT(t,e){let r=le.default.relative(e,t);return r===""||!r.startsWith("..")&&!le.default.isAbsolute(r)}function PT(){return[(0,Ro.homedir)(),(0,Ro.tmpdir)(),Be].flatMap(t=>{let e=le.default.resolve(t);return[e,Lp(e)]})}function Up(t){let e=PT(),r=le.default.resolve(t);if([le.default.resolve(Be),Lp(le.default.resolve(Be))].some(s=>OT(r,s)))return null;for(let s=0;s<MT;s++){if(e.includes(r))return null;let o=le.default.dirname(r);if(o===r)return null;if(AT.some(i=>(0,xr.existsSync)(le.default.join(r,i))))return r;r=o}return null}function xc(t,e){let r=le.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}),Nc}return r}function xp(){try{return(0,xr.statSync)(V).mtimeMs}catch{return-1}}function $p(){let t=xp();if(t===-1)return F.getAllDefaults();if(Io&&Io.mtimeMs===t)return Io.settings;let e=F.loadFromFile(V);return Io={mtimeMs:xp(),settings:e},e}function Bp(){let t=process.env[kT]??$p().MEMINDEX_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function Wp(){let t=process.env[xT]??$p().MEMINDEX_PROJECT_ENVIRONMENTS;return(!vo||vo.raw!==t)&&(vo={raw:t,environments:Pp(t)}),vo.environments}function NT(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 jp(t,e){return e.status===0&&e.stdout?NT(e.stdout):(f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},e.error),null)}function Hp(t){return Bp()?(kr.has(t)||kr.set(t,jp(t,In(t,["remote","get-url","origin"]))),kr.get(t)??null):null}async function CT(t){if(!Bp())return null;if(!kr.has(t)){let e=await Tn(t,["remote","get-url","origin"]);if(wn(e))return null;kr.set(t,jp(t,e))}return kr.get(t)??null}function DT(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Nc;let r=Ee(t,e),n=kc(r,Wp());if(n)return n;let s=Dp(r),o=s?Hp(s):null;if(o)return o;let i=s??Up(r)??r;return xc(t,i)}function Xp(t,e){return e===t?t:`${t}/${e}`}function FT(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=le.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||le.default.isAbsolute(r)?null:r.split(le.default.sep).join("/")}function Ao(t,e=process.platform){if(!t||t.trim()==="")return Kp(t,e);let r=Ee(t,e),n=Dp(r),s=n?Hp(n):null;return Gp(t,r,n,s)}async function Mn(t,e=process.platform){if(!t||t.trim()==="")return Kp(t,e);let r=Ee(t,e),n=await RT(r),s=n?await CT(n):null;return Gp(t,r,n,s)}function Kp(t,e){let r=DT(t,e);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function Gp(t,e,r,n){let s=LT(t,e,r),o=n?Np(s,n,"git-remote"):s,i=kc(e,Wp());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 LT(t,e,r){let n=r?null:Up(e),s=xc(t,r??n??e),o=r??e,i=Rp(o);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${FT(i,o)??s}`,u=s!==a?[s]:[]):(c=Xp(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&&le.default.resolve(n)!==le.default.resolve(e)){let a=xc(t,e);if(a!==s&&a!==Nc)return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,s],keySource:"path"}}return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}var le,xr,Ro,TT,Nc,IT,vT,Pr,AT,MT,kT,Io,xT,vo,kr,nr=E(()=>{"use strict";le=_e(require("path"),1),xr=require("fs"),Ro=require("os");qt();N();Ie();M();wo();Ap();kp();TT="CLAUDE_PROJECT_DIR",Nc="unknown-project";IT=3e4,vT=500,Pr=new Map;AT=[".memindex-project",".memindex.json"],MT=64;kT="MEMINDEX_PROJECT_NAME_SOURCE",Io=null;xT="MEMINDEX_PROJECT_ENVIRONMENTS",vo=null;kr=new Map});function BT(t){try{return(0,ye.realpathSync)(t)}catch{return null}}function Cc(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function WT(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,Lc.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 On(t={}){let e=Object.keys(t).length===0;if(e&&Dc!==void 0)return Dc;let r=jT(t);return e&&r!==null&&(Dc=r),r}function zp(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 jT(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,Fc.homedir)(),o=t.pathExists??ye.existsSync,i=t.lookupInPath??WT,a=t.realpath??BT,c=e==="win32"?[n.BUN,n.BUN_PATH,...zp(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,...zp(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 HT(){let t=B.dataDir();return(0,ye.mkdirSync)(t,{recursive:!0}),t}function XT(t,e,r,n=process.platform,s=(0,ye.existsSync)(Vp)){let o=n!=="win32"&&s;return{command:o?Vp:t,args:o?[t,e,"--daemon"]:[e,"--daemon"],options:{detached:!0,stdio:"ignore",cwd:HT(),env:r}}}function Pn(t,e,r,n=process.platform){let{command:s,args:o,options:i}=XT(t,e,r,n),a=uc(s,o,i);if(a.on("error",c=>{f.error("SYSTEM",$T,{runtimePath:t,execPath:s},c)}),a.pid!==void 0)return a.unref(),a.pid}var me,Fc,ye,Lc,zC,VC,$T,Dc,Vp,Uc=E(()=>{"use strict";me=_e(require("path"),1),Fc=require("os"),ye=require("fs"),Lc=require("child_process");lc();M();Sn();Ec();yn();Ip();nr();wo();N();it();zC=B.dataDir(),VC=B.workerPid(),$T="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.";Vp="/usr/bin/setsid"});function $c(){return F.loadFromFile(V).MEMINDEX_WORKER_HOST}function qp(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Jp(t,e,r="GET",n=sr){let s={method:r,signal:AbortSignal.timeout(Math.max(1,n))},o=await fetch(`http://${qp($c())}:${t}${e}`,r==="GET"||r==="HEAD"?s:En(s)),i="";try{i=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:i}}async function Zp(t,e=sr){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${qp($c())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(s)})}let n=await Mo(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function Mo(t,e=sr){return(await KT(t,e)).occupancy}function KT(t,e=sr){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"}):kf(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,$c())}catch{try{i.close()}catch{}u({occupancy:"indeterminate"})}})}async function GT(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let i=s-Date.now();if((await Jp(t,e,"GET",Math.min(sr,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 Qp(t,e=3e4){return GT(t,"/api/health",e,"Service not ready yet, will retry")}async function zT(t,e=sr){try{let r=await Jp(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 eg(t,e,r=sr){let n=e??"unknown",s=await zT(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}var Yp,sr,Oo=E(()=>{"use strict";Yp=_e(require("net"),1);M();Ie();N();qs();nc();it();sr=5e3});var tg=E(()=>{"use strict";M();yn()});var rg=E(()=>{"use strict";Uc();Oo();tg()});function ng(t){let e=VT.exec(t.trim());if(!e)return null;let r=e[4]===void 0?[]:e[4].split(".");return r.some(n=>n.length>1&&n.startsWith("0")&&Bc.test(n))?null:{core:[Number(e[1]),Number(e[2]),Number(e[3])],pre:r}}function YT(t,e){if(t.length===0||e.length===0)return e.length-t.length;for(let r=0;r<Math.min(t.length,e.length);r++){let n=Bc.test(t[r]),s=Bc.test(e[r]);if(n&&s){let o=Number(t[r])-Number(e[r]);if(o!==0)return o}else{if(n!==s)return n?-1:1;if(t[r]!==e[r])return t[r]<e[r]?-1:1}}return t.length-e.length}function qT(t,e){let r=ng(t),n=ng(e);if(r===null||n===null)return null;for(let s=0;s<3;s++)if(r.core[s]!==n.core[s])return r.core[s]-n.core[s];return YT(r.pre,n.pre)}function sg(t,e){let r=qT(t,e);return r===null?"unreadable":r>0?"upgrade":r<0?"plugin-older":"same"}var VT,Bc,og=E(()=>{"use strict";VT=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,Bc=/^\d+$/});function cg(){return(0,Po.join)(x(),"spawn.lock")}function ig(t){try{let e=JSON.parse((0,ae.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function JT(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function ko(){let t=cg(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,ae.mkdirSync)((0,Po.dirname)(t),{recursive:!0}),(0,ae.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,ae.statSync)(t).mtimeMs}catch{continue}let a=ig(t),c=null;if(a===null)try{c=(0,ae.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-i<=ag&&JT(a)!==!1)return!1;let l;try{l=(0,ae.statSync)(t).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(ig(t)!==a)return!1}else try{if((0,ae.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,ae.unlinkSync)(t)}catch{return!1}}return!1}function kn(){let t=cg();try{if(JSON.parse((0,ae.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,ae.unlinkSync)(t)}catch{}}var Po,ae,ag,mD,ug=E(()=>{"use strict";Po=require("path"),ae=require("fs");N();M();ag=9e4,mD=ag/3});function lg(t){return ZT.test(t.trim())}function QT(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 No(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function eI(t){try{let e=await xo("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:No(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 tI(t,e){try{let r=await xo("netstat",["-ano"],{timeout:No(15e3,e),windowsHide:!0,maxBuffer:16777216});return aI(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 rI(t,e){try{let r=await xo("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:No(1e4,e),maxBuffer:1048576});return nI(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 nI(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]}function sI(t,e){let r=e.toString(16).toUpperCase().padStart(4,"0"),n=[];for(let s of t.split(/\r?\n/).slice(1)){let o=s.trim().split(/\s+/);o.length<10||o[1].split(":").pop()?.toUpperCase()===r&&o[3]==="0A"&&o[9]!=="0"&&n.push(o[9])}return n}function oI(t,e={}){let r=e.deadlineAt??null,n=e.now??Date.now,s=()=>r!==null&&n()>=r;if(s())return null;let o=new Set,i=!1;for(let u of["/proc/net/tcp","/proc/net/tcp6"]){if(s())return null;try{for(let l of sI((0,He.readFileSync)(u,"utf8"),t))o.add(l);i=!0}catch{}}if(!i||s())return null;if(o.size===0)return[];let a;try{a=(0,He.readdirSync)("/proc")}catch{return null}let c=new Set;for(let u of a){if(s())return null;if(!/^\d+$/.test(u))continue;let l;try{l=(0,He.readdirSync)(`/proc/${u}/fd`)}catch{continue}for(let d of l){if(s())return null;try{let p=/^socket:\[(\d+)\]$/.exec((0,He.readlinkSync)(`/proc/${u}/fd/${d}`));if(p&&o.has(p[1])){c.add(Number.parseInt(u,10));break}}catch{}}}return s()?null:[...c]}async function iI(t,e){if(process.platform==="linux")try{return(0,He.readFileSync)(`/proc/${t}/cmdline`,"utf8").split("\0").filter(Boolean).join(" ")||null}catch{return null}try{let n=(await xo("ps",["-p",String(t),"-o","command="],{timeout:No(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function aI(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 uI(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let n=(l,d={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:l,...d}),{reclaimed:!1,reason:l,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 l=0;l<2;l++)if(l>0&&await e.sleep(mg),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=e.readHeartbeat();if(i?.pid===r.pid){let l=e.now(),d=Math.max(0,l-i.beatAtMs),p=Math.max(0,l-i.lastResponseAtMs);if(d<e.heartbeatStaleMs&&p<e.maxSilentProtectionMs)return n("owner-progressing",{heartbeatAgeMs:d,sinceLastResponseMs:p})}let a=await e.readIdentity(r.pid),c=r.startToken!==void 0&&a.startToken!==null&&a.startToken!==r.startToken;if(c||a.cmdline===null||!cI.test(a.cmdline))return n("owner-identity-mismatch",{tokenMismatch:c,hasCmdline:a.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:a.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(l){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},l instanceof Error?l:new Error(String(l))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let u=await e.listOwners(t);return u!==null&&u.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:u}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function lI(t,e,r,n){let s=Et(t),o=e?(await r(n))?.find(i=>i.pid===t)?.cmdline??null:await iI(t,n);return Re(t,s)?{startToken:s,cmdline:o}:{startToken:null,cmdline:null}}async function hg(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,o=b=>s!==null&&s-n()<b,i=()=>s===null?void 0:Math.max(1,s-n());if(o(dg))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:i(),neededMs:dg}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((b,P)=>r()?tI(b,P):process.platform==="linux"?Promise.resolve(oI(b,{deadlineAt:s,now:n})):rI(b,P)),c=b=>a(b,i()),u=e.readTable??eI,l=()=>u(i()),d=e.killTree??((b,P)=>Ae(b,P)),p=e.dataDir??(()=>W),g=e.readIdentity??((b,P)=>lI(b,r(),u,P)),m=await uI(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??ot,probeHealth:e.probeHealth??(b=>Qp(b,gg)),readIdentity:b=>g(b,i()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??Qd(),readHeartbeat:e.readHeartbeat??(()=>gI()),heartbeatStaleMs:e.heartbeatStaleMs??pI(),maxSilentProtectionMs:e.maxSilentProtectionMs??dI,now:n,sleep:e.sleep??(b=>new Promise(P=>setTimeout(P,b))),hasKillBudget:()=>!o(Wc)});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(b=>q(b)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let w=new Map;for(let b of _){let P=w.get(b.ppid);P?P.push(b):w.set(b.ppid,[b])}let T=new Map,R=new Set,I=b=>{for(let P of w.get(b)??[])R.has(P.pid)||(R.add(P.pid),I(P.pid),lg(P.name)&&T.set(P.pid,P))};for(let b of h)I(b);let y=p();if(y)for(let b of _)T.has(b.pid)||lg(b.name)&&QT(b.cmdline,y)&&T.set(b.pid,b);if(T.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:[...T.values()].map(b=>({pid:b.pid,name:b.name}))});let v=[];for(let b of T.values()){if(o(Wc))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(b.pid,{expectedStartToken:b.startToken,signalMode:"immediate"}),v.push(b.pid)}catch(P){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:b.pid},P instanceof Error?P:new Error(String(P))),{reclaimed:!1,reason:"kill-failed",killedPids:v}}}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: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:A}),{reclaimed:!1,reason:"still-bound",killedPids:v})}function pI(t=process.env,e=V){let r=t.MEMINDEX_WORKER_HEARTBEAT_STALE_MS??F.loadFromFile(e,!1,{readOnly:!0}).MEMINDEX_WORKER_HEARTBEAT_STALE_MS,n=Number(r);return Number.isSafeInteger(n)&&n>=1e4&&n<=36e5?n:fI}function gI(t=B.workerHeartbeat()){try{let e=JSON.parse((0,He.readFileSync)(t,"utf8"));if(e&&Number.isSafeInteger(e.pid)&&Number.isFinite(e.beatAtMs)&&Number.isFinite(e.lastResponseAtMs))return{pid:e.pid,beatAtMs:e.beatAtMs,lastResponseAtMs:e.lastResponseAtMs}}catch{}return null}var fg,He,pg,xo,ZT,cI,gg,mg,Wc,dg,dI,fI,_g=E(()=>{"use strict";fg=require("node:child_process"),He=require("node:fs"),pg=require("node:util");M();Ar();it();yn();Oo();so();rt();N();Ie();xo=(0,pg.promisify)(fg.execFile),ZT=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;cI=/worker-service/i,gg=1500,mg=1e3,Wc=5500,dg=2*gg+mg+Wc;dI=6e5,fI=12e4});function Eg(t){try{return(0,Nr.realpathSync)(t)}catch{return t}}function hI(t,e){let r=Pt.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!Pt.default.isAbsolute(r)}function yg(t){let e;try{let s=JSON.parse((0,Nr.readFileSync)(Pt.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=Pt.default.join(t,"node_modules"),n=e.filter(s=>!(0,Nr.existsSync)(Pt.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,Sg.createRequire)(Pt.default.join(r,"noop.js")),o=Eg(Pt.default.join(r,"zod"));for(let i of mI)try{let a=s.resolve(i,{paths:[r]});hI(Eg(a),o)||n.push(i)}catch{n.push(i)}}return n}var Nr,Sg,Pt,mI,bg=E(()=>{"use strict";Nr=require("fs"),Sg=require("module"),Pt=_e(require("path"),1),mI=["zod/v3","zod/v4","zod/v4-mini"]});function Ig(){return Co.default.join(x(),"worker-standby.json")}function Xc(){return Co.default.join(x(),"worker-standby-attempt.json")}function Kc(){return Co.default.join(x(),"worker-standby-failure.json")}function Gc(t){try{return JSON.parse((0,Do.readFileSync)(t,"utf-8"))}catch{return null}}function zc(t){try{(0,Do.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 Fo(){let t=Gc(Ig());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 Lo(t){if(t!==void 0){let e=Fo();if(e!==null&&e.pid!==t)return}zc(Ig())}function _I(){let t=Gc(Kc());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 vg(t,e,r=new Date){try{$(Kc(),{buildKey:t,failedAt:r.toISOString(),reason:e})}catch(n){f.warn("SYSTEM","Could not save the failed worker update attempt",{error:n instanceof Error?n.message:String(n)})}}function Rg(){zc(Kc())}function Ag(t,e=Date.now()){if(t===null)return null;let r=_I();if(r===null||r.buildKey!==t)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||e-n>=Hc?null:r}function Mg(){let t=Gc(Xc());return!t||typeof t.buildKey!="string"||typeof t.launchedAtMs!="number"||!Number.isFinite(t.launchedAtMs)?null:{buildKey:t.buildKey,launchedAtMs:t.launchedAtMs}}function Og(t){try{$(Xc(),t)}catch(e){f.debug("SYSTEM","Could not save the worker update attempt",{error:e instanceof Error?e.message:String(e)})}}function Pg(){zc(Xc())}var Co,Do,wg,jc,Tg,Hc,kg=E(()=>{"use strict";Co=_e(require("path"),1),Do=require("fs");N();oe();M();wg="MEMINDEX_WORKER_STANDBY",jc=12e4,Tg=2e4,Hc=10*6e4});function Qc(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 zg(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 bI(t){return zg()?{...t,verbose:!0}:t}function wI(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 TI(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=wI(r),o=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},o),mt(`[memindex] fetch verbose: ${n} ${t} ${o}
22
- `)}async function Fn(t,e={}){let r=bI(e);try{return await fetch(t,r)}catch(n){throw zg()&&TI(t,e,n),n}}async function Cr(t,e={},r){try{return await Fn(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 II(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 Vg(t,e,r){let n=II(r,e.signal),s;try{s=await Fn(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 vI(t,e,r){let n=await Vg(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 xg(){return U.default.join(F.get("MEMINDEX_DATA_DIR"),"settings.json")}function tu(t={}){return t.readOnly?F.loadFromFile(xg(),!0,t):(Uo!==null||(Uo=F.loadFromFile(xg())),Uo)}function Ng(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Yg(t,e,r){let n=process.env[t];if(n!==void 0){let i=Ng(n,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=tu()[t],o=Ng(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 te(t={}){if(!t.readOnly&&Vc!==null)return Vc;let e=parseInt(tu(t).MEMINDEX_WORKER_PORT,10),r=e===Ha()&&gn()?Ka(x()):e;return t.readOnly||(Vc=r),r}function Xo(t={}){if(!t.readOnly&&Yc!==null)return Yc;let e=tu(t).MEMINDEX_WORKER_HOST;return t.readOnly||(Yc=e),e}function RI(){return $o!==null||($o=Yg("MEMINDEX_API_TIMEOUT_MS",Rt(ie.API_REQUEST),SI)),$o}function qg(){return Bo!==null||(Bo=Math.min(Yg("MEMINDEX_SESSION_INIT_TIMEOUT_MS",ln(),yI),ef())),Bo}function Jg(t){return t===null?null:Math.max(0,t-Date.now())}function jo(t){let e=Jg(t);return e!==null&&e<eu}function Oe(t,e){let r=Jg(e);return r===null?t:Math.max(1,Math.min(t,r))}function Dn(t){return`http://${ic(Xo())}:${te()}${t}`}function AI(t){let e=t.split("?")[0].toLowerCase().replace(/\/+$/,"");return e==="/api/health"||e==="/api/readiness"||e==="/api/ready"}async function OI(t){if(!await Qs(Dn(""),{timeoutMs:t,fetchImpl:Fn}))throw Cg||(Cg=!0,f.warn("SECURITY","The listener on the worker port did not prove it is this install's worker; nothing was sent to it",{port:te(),host:Xo()})),new Rr(MI)}async function be(t,e={}){let r=e.method??"GET",n=Dn(t),s={method:r};e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body);let o=AI(t),i=Date.now(),a=e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0?e.timeoutMs:e.timeoutMs??RI(),c=()=>Date.now()-i,u=l=>l===void 0||l<=0?l:Math.max(1,l-c());try{o||await OI(a!==void 0&&a>0?Math.min(Pe,a):Pe);let l=o?s:En(s);if(e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0){let p=await vI(n,l,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:u(e.timeoutMs)});return new Response(p.text.length>0?p.text:null,{status:p.status,statusText:p.statusText,headers:p.headers})}let d=u(a)??0;return d>0?await Cr(n,l,d):await Fn(n,l)}catch(l){throw l instanceof Rr||Lf(),l}}async function PI(t){return(await be("/api/health",{timeoutMs:t})).ok}async function Dg(t=Pe){return(await be("/api/readiness",{timeoutMs:t})).ok}function Zg(t){let e=(0,k.existsSync)(U.default.join(t,"plugin","scripts"))?U.default.join(t,"plugin"):t;return U.default.join(e,"scripts","worker-service.cjs")}function kI(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 xI(t=U.default.join(U.default.dirname(U.default.dirname(wr)),"cache","memindex","memindex")){try{return(0,k.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>U.default.join(t,e)).filter(e=>{try{if(!(0,k.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,k.existsSync)(U.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:Zg(e),version:U.default.basename(e)}))}catch{return[]}}function Fg(t){try{let e=JSON.parse((0,k.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function NI(){return{cacheRoot:U.default.join(U.default.dirname(U.default.dirname(wr)),"cache","memindex","memindex"),marketplaceRoot:wr,cwd:process.cwd()}}function ru(t=NI()){let e=process.env.MEMINDEX_WORKER_SCRIPT_PATH?.trim();if(e){if((0,k.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing MEMINDEX_WORKER_SCRIPT_PATH override",{override:e})}let r=Lg([...xI(t.cacheRoot),{scriptPath:Zg(U.default.join(t.marketplaceRoot,"plugin")),version:Fg(U.default.join(t.marketplaceRoot,"package.json"))}]);return r||!Yd()?r:Lg([{scriptPath:U.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:Fg(U.default.join(t.cwd,"package.json"))}])}function CI(t){return U.default.dirname(U.default.dirname(t))}function DI(t){return yg(CI(t.scriptPath)).length===0}function Lg(t,e=DI){let r=t.filter(n=>(0,k.existsSync)(n.scriptPath));return r.length===0?null:(r.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:kI(n.version,s.version)),r.find(e)??r[0])}function FI(){return ru()?.scriptPath??null}async function LI(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(jo(e))return!1;if(await am(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,Oe(r,e))),r*=2)}return!1}function Ug(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function $g(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function UI(t){let e;try{e=await Vg(Dn("/api/ready"),{method:"GET"},{idleTimeoutMs:EI,absoluteCapMs:Math.max(1,t)})}catch(o){return Ug(o)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:$g(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 Ho(),await r(),{outcome:"unsupported"};let s=null;try{for await(let o of Bf(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 Ho(),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 $g(o)?(Ho(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):Ug(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 $I(t){if(t<=0)try{return await Dg()?{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 Dg(Math.max(1,Math.min(Pe,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 kt(t=ir){let e=t>0?t:Pe,r=await UI(e);return r.outcome==="ready"&&GI(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),$I(t))}async function BI(t=Pe){try{let r=await(await be("/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 WI(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await Mo(te(),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 Qg(t,e){if(!t)return null;try{let r=(0,k.statSync)(t.scriptPath);return JSON.stringify([t.scriptPath,e,r.size,r.mtimeMs,r.ctimeMs])}catch{return null}}function em(){return U.default.join(x(),"worker-version-recycle.json")}function jI(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,k.readFileSync)(em(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function Bg(t,e=null,r=Pe){let n=await BI(r);if(n!==null&&n!==t){if(e!==null)try{$(em(),{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 nu(){return U.default.join(x(),"worker-unresponsive.json")}function HI(){try{let t=JSON.parse((0,k.readFileSync)(nu(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function Ho(){let t=nu();if((0,k.existsSync)(t))try{(0,k.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function XI(t=Date.now()){let e=ot()?.pid??null;if(e===null)return!1;let r=HI();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=tm;try{$(nu(),{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 su(){return U.default.join(x(),"worker-never-ready-recycle.json")}function KI(){try{let t=JSON.parse((0,k.readFileSync)(su(),"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 rm(t){try{$(su(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function GI(){let t=su();if((0,k.existsSync)(t))try{(0,k.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function nm(t){return Qg(t,t?.version??"unknown")??"unresolved-worker-bundle"}function sm(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function om(t,e){if(t.outcome==="unresponsive"&&!XI())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:tm}),!1;let r=sm(t),n=KI();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:U.default.join(x(),"logs")}),rm({...n,refusalLogged:!0})),!1):!0}function im(t,e){rm({buildKey:e,failureMessage:sm(t)}),Ho()}async function am(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await PI(Math.min(Pe,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function ou(t,e){let r=ot();if(r===null||r.port!==te())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:te(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await Ae(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 WI(Oe(5e3,t))?!0:(e("stale port release")||(ar=te(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:te(),fix:Ko})),!1)}function Jc(t,e){return`http://127.0.0.1:${t}${e}`}async function cm(t,e){if(e<=0)return{answered:!1,version:null};try{let n=await(await Cr(Jc(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 um(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)})}Lo(t.pid)}async function zI(t,e,r,n){let s=await VI(t,e,r,n);return s.kind!=="out-of-budget"&&Pg(),s}async function VI(t,e,r,n){let s=Fo(),o=s===null?null:await cm(s,Oe(Pe,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(xn/1e3)} seconds; the worker log has the reason`};if(s!==null&&o!==null)if(o.answered)um(s);else{let d=Date.parse(s.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<jc&&q(s.pid)){let g=Math.min(d+jc,Math.max(d+xn,Date.now()+2e3)),m=await qc(e,g,n,i);return m.kind==="failed"&&Lo(s.pid),m}Lo(s.pid)}let a=r===null?null:Mg();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=xn?i:qc(e,a.launchedAtMs+xn,n,i);let c=On();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=Pn(c,t,je({...process.env,MEMINDEX_WORKER_PORT:String(te()),[wg]:"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&&Og({buildKey:r,launchedAtMs:l}),qc(e,l+xn,n,i)}async function qc(t,e,r,n){let s=Math.min(e,r??Number.POSITIVE_INFINITY);for(;Date.now()<s;){let o=Fo();if(o!==null){let a=await cm(o,Math.min(1e3,s-Date.now()));if(a.answered)return a.version===t?{kind:"ready",record:o}:(um(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 YI(t,e){try{if(!await Qs(Jc(t.port,""),{timeoutMs:e,fetchImpl:Fn}))return"the standby worker did not prove it holds this install's secret";let r=await Cr(Jc(t.port,"/api/admin/promote"),En({method:"POST"}),e);if(r.ok)return null;let n=await r.json().catch(()=>({}));return typeof n.message=="string"?n.message:`HTTP ${r.status}`}catch(r){return r instanceof Error?r.message:String(r)}}async function qI(t){let{scriptPath:e,pluginVersion:r,workerVersion:n,buildKey:s,deadlineAt:o,outOfBudget:i}=t,a=n??"unknown",c=Ag(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=ot();if(u===null||u.port!==te())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:te(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),"failed";if(!ko())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 zI(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&&vg(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(Hc/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 ou(o,i))return"failed";l=!0;let p=await YI(d.record,Oe(1e4,o));return p===null?(Rg(),f.info("SYSTEM","The updated worker took over from the old one",{from:n,to:r,pid:d.record.pid}),"promoted"):(f.warn("SYSTEM","The updated worker could not take over the worker port; starting a new worker the usual way",{pluginVersion:r,reason:p}),"old-stopped")}finally{l||kn()}}async function Ln(t){let e=t===void 0?null:Date.now()+t,r=S=>jo(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:Oe(Pe,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),o=ru(),i=null,a=null,c=!1,u=!1,l=!1,d=null,p=null,g=to(z());if(r("health probe"))return!1;if(await am(s)){if(r("version probe"))return!1;let{matches:S,pluginVersion:w,workerVersion:T}=await eg(te(),o?.version??null,n());if(w!=="unknown"&&(i=w),S){if(r("readiness wait"))return!1;let R=await kt(Oe(ir,e));if(R.outcome==="ready")return i!==null&&!jo(e)&&await Bg(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=nm(o),!om(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:T})}else{let R=T===null?"unreadable":sg(w,T);if(R!=="upgrade")return Wg||(Wg=!0,f.info("SYSTEM",R==="plugin-older"?"This plugin is older than the running worker, so the running worker stays; update this session (npx memindex update) to use the newer one":"Could not tell which of the plugin and the running worker is newer, so the running worker stays",{pluginVersion:w,workerVersion:T})),r("readiness wait")?!1:(await kt(Oe(ir,e))).outcome==="ready";if(g)return f.warn("SYSTEM","Worker version differs from the installed plugin; MEMINDEX_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:w,workerVersion:T}),r("readiness wait")?!1:(await kt(Oe(ir,e))).outcome==="ready";if(a=Qg(o,w),jI(a,T))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:w,workerVersion:T,scriptPath:o?.scriptPath}),r("readiness wait")?!1:(await kt(Oe(ir,e))).outcome==="ready";f.info("SYSTEM","Worker version changed \u2014 starting the new worker before stopping the old one",{pluginVersion:w,workerVersion:T});let I=await qI({scriptPath:o?.scriptPath??null,pluginVersion:w,workerVersion:T,buildKey:a,deadlineAt:e,outOfBudget:r});if(I==="failed")return!1;if(I==="kept-old")return r("readiness wait")?!1:(await kt(Oe(ir,e))).outcome==="ready";u=!0,l=I==="promoted"}if(!u&&!await ou(e,r))return!1;d!==null&&p!==null&&im(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&&kn(),!1;let h=u||ko();try{if(h&&!l){if(!c&&!await JI(s,e,m))return!1;let w=On();if(!w)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:w,scriptPath:m});try{if(Pn(w,m,je({...process.env,MEMINDEX_WORKER_PORT:String(te())}),process.platform)===void 0)return!1}catch(T){return T instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:w,scriptPath:m},T):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:w,scriptPath:m,error:String(T)}),!1}}else h||f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await LI({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)"),ot()===null&&await Zp(te(),e===null?void 0:Oe(5e3,e))&&(ar=te(),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:ar,fix:Ko}))),!1}finally{h&&kn()}if(r("readiness wait"))return!1;let _=await kt(Oe(ir,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&&!jo(e)&&await Bg(i,a,n()),!0)}async function JI(t,e,r){let n=te(),s=t-Date.now();if(s<=0)return!1;let o=await Mo(n,s);if(o==="free")return!0;if(o==="unbindable")return Zc=n,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:n,host:Xo(),fix:Ja}),!1;if(o==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:n}),!1;let i=await hg(n,{deadlineAt:e});return i.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:n,killedPids:i.killedPids}),!0):(i.reason==="out-of-budget"&&e!==null&&tv(n,r),ot()===null&&(ar=n),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:n,reclaimReason:i.reason,...ar===n?{fix:Ko}:{}}),!1)}function ev(t){let e;try{e=Date.now()-(0,k.statSync)(t).mtimeMs}catch{return!1}if(e<ZI)return!0;if(e>=QI)return!1;try{let{daemonPid:r}=JSON.parse((0,k.readFileSync)(t,"utf8"));return!Number.isInteger(r)||r<=0||q(r)}catch{return!0}}function tv(t,e){let r=U.default.join(x(),"reclaim-handoff.json");if(ev(r))return;let n=On();if(!n||!e)return;let s=i=>{$(r,{hookPid:process.pid,daemonPid:i,port:t})},o=()=>{try{(0,k.unlinkSync)(r)}catch{}};try{s(null)}catch(i){f.warn("SYSTEM","Could not record the reclaim handoff; skipping detached reclaim",{port:t},i instanceof Error?i:new Error(String(i)));return}try{let i=Pn(n,e,je({...process.env,MEMINDEX_WORKER_PORT:String(t)}),process.platform);if(i===void 0){o();return}if(i>0)try{s(i)}catch{}f.info("SYSTEM","Handed the port reclaim to a detached worker daemon",{port:t,daemonPid:i})}catch(i){o(),f.warn("SYSTEM","Could not launch the detached reclaim daemon",{port:t},i instanceof Error?i:new Error(String(i)))}}async function rv(t){if(or!==void 0)return or;try{let e=Za(),n=await(await Cr(rc(Dn(""),e),{method:"GET",redirect:"error"},t)).json();Qa(n.proof,e)&&tc(Dn("")),or=mf(n.dataDir,x())==="foreign"?String(n.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)}),or=null}return or!==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:or,dataDir:x(),port:te()}),or}async function nv(t){return Wo!==null||(Wo=await Ln(t)),Wo}async function sv(t){let e=Date.now()+t,r=()=>e-Date.now(),n=u=>r()>=eu?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:u,budgetMs:t}),!0),s=await kt(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(!!to(z()))return jg(e);let i=On(),a=FI();if(!i||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let u=nm(ru());if(!om(s,u)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await ou(e,n)))return!1;im(s,u)}let c=ko();try{return c&&Pn(i,a,je({...process.env,MEMINDEX_WORKER_PORT:String(te())}),process.platform)===void 0?!1:await jg(e)}catch(u){return f.debug("SYSTEM","Bounded worker startup failed",{error:u instanceof Error?u.message:String(u)}),!1}finally{c&&kn()}}async function jg(t){for(;t-Date.now()>0;){let e=await kt(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 Go(){return U.default.join(W,"state")}function pm(){return U.default.join(Go(),"hook-failures.json")}function gm(){return U.default.join(Go(),"hook-failures.lock")}async function iu(t=dm){let e=Go(),r=gm(),n=(0,Gg.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),o=Date.now()+t;for(;Date.now()<=o;)try{return(0,k.mkdirSync)(e,{recursive:!0}),(0,k.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,k.statSync)(r).mtimeMs}catch{continue}if(Date.now()-u>fm){let l;try{l=(0,k.statSync)(r).mtimeMs}catch{continue}if(l===u)try{(0,k.unlinkSync)(r);continue}catch{}}await new Promise(l=>setTimeout(l,iv))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function au(t){let e=gm();try{if(JSON.parse((0,k.readFileSync)(e,"utf-8")).token!==t)return;(0,k.unlinkSync)(e)}catch{}}function cv(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(-lm):void 0}}function Cn(){try{return cv((0,k.readFileSync)(pm(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function cu(t){let e=Go(),r=pm(),n=`${r}.tmp`;try{return(0,k.existsSync)(e)||(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(n,JSON.stringify(t),"utf-8"),(0,k.renameSync)(n,r),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function uv(){try{let e=z().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return ov}function mm(t){let e=Zc!==null?`The worker cannot bind port ${Zc} on ${Xo()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Ja}.`:ar!==null?`Port ${ar} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${Ko}.`:"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 Nn(){if(lv){if(Xg)return Cn().consecutiveFailures;Xg=!0}let t=await iu();if(t===null)return Cn().consecutiveFailures;let e,r=!1;try{let n=Cn();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=uv();r=e.consecutiveFailures>=s&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let o=cu(e);r=r&&o}finally{au(t)}return r&&(await bp("hook_failed",{...Hg!==null?{hook_type:Hg}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),mt(`${mm(e.consecutiveFailures)}
23
- `)),e.consecutiveFailures}async function hm(t){if(!t)return null;let e=await iu();if(e===null)return null;try{let r=Cn(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:cu({...r,notifiedSessionIds:[...n,t].slice(-lm)})?mm(r.consecutiveFailures):null}finally{au(e)}}async function Kg(){let t=await iu(av);if(t!==null)try{let e=Cn();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;cu({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{au(t)}}function _m(t){return typeof t=="object"&&t!==null&&t[St]===!0}async function Em(t,e,r,n={}){let s=Date.now(),o=n.workerStartupTimeoutMs!==void 0;if(!(o?await sv(n.workerStartupTimeoutMs):await nv(n.timeoutMs)))return to(z())?{continue:!0,reason:"worker_autostart_disabled",[St]:!0}:(o||await Nn(),{continue:!0,reason:"worker_unreachable",[St]:!0});let a=n.timeoutMs===void 0?Pe:Math.max(1,Math.min(Pe,n.timeoutMs-(Date.now()-s)));if(await rv(a)!==null)return await Nn(),{continue:!0,reason:"worker_foreign_data_dir",[St]:!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<eu)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),o||await Nn(),{continue:!0,reason:"worker_budget_exhausted",[St]:!0};c.timeoutMs=d}let u;try{u=await be(t,c)}catch(d){if(d instanceof Rr)return await Nn(),{continue:!0,reason:"worker_unverified",[St]:!0};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",[St]:!0}}if(!u.ok){let d=await u.text().catch(()=>"");if(await Kg(),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}`,[St]:!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 Nn(),{continue:!0,reason:"worker_body_read_failed",[St]:!0}}if(await Kg(),l.length!==0)try{return JSON.parse(l)}catch{return l}}var U,Gg,k,Pe,ir,xn,EI,SI,yI,eu,Vc,Yc,Uo,$o,Bo,Cg,MI,tm,Wg,Ko,ar,Zc,ZI,QI,Wo,or,ov,lm,dm,iv,fm,av,Hg,lv,Xg,St,xt=E(()=>{"use strict";nc();U=_e(require("path"),1),Gg=require("crypto"),k=require("fs");M();rt();Wf();Ie();N();st();jf();Hf();ac();Ga();yn();it();js();wp();rg();og();Oo();qs();Uc();ug();_g();Sn();Ar();oe();bg();kg();ac();Pe=Qc("MEMINDEX_HEALTH_TIMEOUT_MS",Rt(ie.HEALTH_CHECK),{min:500,max:3e5}),ir=Qc("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",Rt(ie.HOOK_READINESS_WAIT),{min:0,max:3e5}),xn=Qc("MEMINDEX_WORKER_STANDBY_WAIT_MS",Tg,{min:500,max:3e5}),EI=5e3,SI={min:500,max:3e5},yI={min:500,max:ie.SESSION_INIT_REQUEST_MAX},eu=100;Vc=null,Yc=null,Uo=null,$o=null,Bo=null;Cg=!1,MI="The program answering on the MemIndex worker port did not prove it holds this install's secret, so MemIndex sent it nothing. Notes wait in the hook spool until the real worker answers. If this keeps happening, run npx memindex doctor.";tm=3e4;Wg=!1;Ko="Set MEMINDEX_WORKER_PORT to a different port in memindex settings, or reboot to release the stuck port",ar=null,Zc=null;ZI=3e4,QI=12e4;Wo=null;ov=3,lm=20,dm=1e3,iv=10,fm=5e3,av=fm+dm;Hg=null;lv=!1,Xg=!1;St=Symbol.for("memindex/worker-fallback")});function uu(t,e){let r=(0,at.normalize)(t),n=(0,at.normalize)(e);if(r===n)return!0;let s=(0,at.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,at.isAbsolute)(s)}function ct(t){if(process.env.MEMINDEX_INTERNAL==="1")return!1;if(!t)return!0;if(uu(t,Xs)||uu(t,hv)||uu(t,_v))return!1;let e=z();return!Rn(t,e.MEMINDEX_EXCLUDED_PROJECTS)}var at,dv,fv,pv,gv,mv,hv,_v,Dr=E(()=>{"use strict";at=require("path");An();st();N();dv="plugins",fv="cache",pv="memindex",gv="memindex",mv="plugin",hv=(0,at.join)(Be,dv,fv,pv,gv),_v=(0,at.join)(wr,mv)});function Ev(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Y(t){if(!t)return Sm;let e=Ev(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:Sm}var Sm,ut=E(()=>{"use strict";Sm="claude"});var ym=E(()=>{"use strict"});function Rm(t){let e=Object.fromEntries(lu.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}wm.lastIndex=a;let l=wm.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}bm.lastIndex=a;let d=bm.exec(t);if(d&&Sv.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 zo(t){let e="",r=0;for(;;){let n=t.indexOf(Tm,r);if(n===-1)break;let s=t.indexOf(Im,n+Tm.length);if(s===-1)break;e+=t.slice(r,n),r=s+Im.length}return r===0?t:e+t.slice(r)}function yv(t){let{text:e,counts:r,total:n}=Rm(t);return n>vm&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:vm,contentLength:t.length}),{stripped:Gs(e.trim(),La()).redacted,counts:r}}function we(t){return yv(t).stripped}function bv(t){return t.includes("<")&&lu.some(e=>t.includes(`<${e}`))}function Un(t){let e=r=>typeof r=="string"?bv(r)&&Rm(r).total>0?we(r):r:Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,s])=>[n,e(s)])):r;return e(t)}function Vo(t){return!t||t.length>Iv?!1:Tv.test(t)}function Am(t){let e=t.trimStart();return vv.some(r=>r.test(e))}var lu,Sv,bm,wm,Tm,Im,vm,wv,Tv,Iv,vv,lt=E(()=>{"use strict";M();Ua();lu=["private","memindex-context","agent-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Sv=new Set(lu),bm=/<([A-Za-z_][A-Za-z0-9_-]*)/y,wm=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;Tm="<system-reminder>",Im="</system-reminder>";vm=100;wv=["task-notification"],Tv=new RegExp(`^\\s*<(${wv.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Iv=256*1024;vv=[/^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 Av(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 Ke(t){return t instanceof Xe}function Mv(t){return t.replace(/\/+$/,"")}function Yo(t){return typeof t=="string"?Y(t):null}function Ov(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var Rv,Xe,qo,cr=E(()=>{"use strict";xt();rt();ut();lt();Rv=Rt(ie.API_REQUEST),Xe=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)}},qo=class{baseUrl;apiKey;timeoutMs;branchRejected=!1;constructor(e){this.baseUrl=Mv(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Rv}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 Xe("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 Xe("invalid_response","id is required for updateObservation");await this.request("PATCH",`/v1/memories/${encodeURIComponent(e)}`,r)}async deleteObservation(e){if(!e)throw new Xe("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=Yo(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 Xe("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:Yo(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:Yo(e.platformSource)}:{},...e.metadata!==void 0?{metadata:Un(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:Yo(e.platformSource)}:{},...e.payload!==void 0?{payload:Un(e.payload)}:{},...e.branch?{branch:e.branch}:{}}}async request(e,r,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new Xe("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 Xe(m?"timeout":"transport",`Server ${e} ${r} failed: ${g}`,{cause:p})},u,l=s.timeoutMs??this.timeoutMs;try{u=await Cr(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)&&Av(p))return this.branchRejected=!0,this.request(e,r,n,s);throw new Xe("http_error",`Server ${e} ${r} returned ${u.status}: ${Ov(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 Xe("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:g})}}}});function Pv(){let e=(z().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function kv(){let t=z(),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 xv(){let{serverBaseUrl:t,apiKey:e,projectId:r}=kv();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 qo(n),projectId:r,serverBaseUrl:t}}function Ge(){if(Pv()!=="server")return{runtime:"worker"};let t=xv();return t||{runtime:"worker"}}function ze(t,e){f.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var Fr=E(()=>{"use strict";st();M();cr()});function Lv(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 Ve(t){let e=(0,gu.createHash)("sha256").update(Lv(t.serverBaseUrl)).update("\0").update(t.projectId).digest("hex").slice(0,16);return(0,Nt.join)(x(),"state","server-outbox",e)}function mu(t){return(0,Nt.join)(t,"outage.json")}function yt(t){return Ke(t)&&t.isFallbackEligible()&&t.kind!=="missing_api_key"}function Uv(){return du=Math.max(Date.now(),du+1),du}function $v(t,e){let r=(0,gu.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16);return`${String(t).padStart(15,"0")}-${e.op}-${r}.json`}function Ct(t,e){(0,K.mkdirSync)(e,{recursive:!0});let r=Un(t),n=Uv(),s=(0,Nt.join)(e,$v(n,r));return $(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 Pm(t){return(0,K.existsSync)(t)?(0,K.readdirSync)(t).filter(e=>e.endsWith(".json")&&e!=="outage.json").sort():[]}function pu(t){try{return Pm(t).length}catch{return 0}}function Bv(t){for(let e of(0,K.readdirSync)(t)){if(!e.endsWith(`.json${fu}`))continue;let r=(0,Nt.join)(t,e);try{if(Date.now()-(0,K.statSync)(r).mtimeMs<Nv)continue;(0,K.renameSync)(r,r.slice(0,-fu.length))}catch{}}}async function hu(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 Wv(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 hu(t,e.request,s,n)}function Om(t,e,r){try{(0,K.mkdirSync)((0,Nt.join)(t,Mm),{recursive:!0}),(0,K.renameSync)(e,(0,Nt.join)(t,Mm,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 Lr(t,e,r={}){let n=r.maxEntries??Dv,s=Date.now()+(r.budgetMs??Fv),o={delivered:0,remaining:0,rejected:0};try{if(!(0,K.existsSync)(e))return o;Bv(e);let i=Pm(e),a=0;for(let c of i){if(a>=n||Date.now()>=s)break;let u=(0,Nt.join)(e,c),l=`${u}${fu}`;try{(0,K.renameSync)(u,l)}catch{continue}try{let p=new Date;(0,K.utimesSync)(l,p,p)}catch{}a++;let d;try{if(d=JSON.parse((0,K.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))),Om(e,l,c),o.rejected++;continue}try{let p=m=>{try{$(l,{...d,entry:{op:"summarize",request:m}})}catch{}},g=a===1?Math.max(s,Date.now()+ie.API_REQUEST):s;await Wv(t,d.entry,g,p),(0,K.unlinkSync)(l),o.delivered++}catch(p){if(yt(p)){(0,K.renameSync)(l,u);break}f.error("HOOK","Hosted server refused a held capture; moved aside",{name:c,op:d.entry.op,status:Ke(p)?p.status:null},p instanceof Error?p:new Error(String(p))),Om(e,l,c),o.rejected++}}o.remaining=pu(e),o.delivered>0&&f.info("HOOK","Sent held captures to the hosted server",{...o}),o.remaining===0&&Hv(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=pu(e)}return o}function jv(t){try{let e=JSON.parse((0,K.readFileSync)(mu(t),"utf-8"));return{notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds:[]}}catch{return{notifiedSessionIds:[]}}}function Hv(t){try{(0,K.unlinkSync)(mu(t))}catch{}}function Xv(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 km(t,e){if(!t)return null;let r=pu(e);if(r===0)return null;let n=jv(e);if(n.notifiedSessionIds.includes(t))return null;try{$(mu(e),{notifiedSessionIds:[...n.notifiedSessionIds,t].slice(-Cv)})}catch{}return Xv(r)}var gu,K,Nt,fu,Mm,Nv,Cv,Dv,Fv,du,$n=E(()=>{"use strict";gu=require("crypto"),K=require("fs"),Nt=require("path");oe();N();rt();M();lt();cr();fu=".sending",Mm="rejected",Nv=120*1e3,Cv=50,Dv=20,Fv=1500;du=0});function Zo(t){return eR.run(t,!0)}function tR(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 rR(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 nR(t){let e=t.replace(Yv," ").toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu)??[],r=[...new Set(e)].slice(0,Vv);return r.length>0?r.join(" or "):null}async function sR(t,e,r,n,s,o,i){if(e.length<20||e==="[media prompt]")return"";let a=nR(e);if(!a)return"";let c=_u(o,i);if(c<Jo)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,aR(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,qv):""}catch(u){return f.warn("HOOK","session-init: server semantic context unavailable",{error:u instanceof Error?u.message:String(u)}),""}}function oR(t){let e=String(t.MEMINDEX_SEMANTIC_INJECT).toLowerCase();return e==="auto"?String(t.MEMINDEX_MODE).toLowerCase()==="personal":e==="true"}function iR(t){let e=String(t.MEMINDEX_READ_ONLY??"").toLowerCase();return e==="1"||e==="true"}async function xm(t,e,r,n,s,o,i){if(!e||e.length<20||e==="[media prompt]")return"";let a=_u(o,i);if(a<Jo)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},Nm(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 aR(t){let e=typeof t=="number"?t:Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?5:e}function _u(t,e){return Math.max(0,e-(Date.now()-t))}function Nm(t,e){return t==="codex"?{workerStartupTimeoutMs:ie.POST_SPAWN_WAIT,timeoutMs:Math.min(Jv,e)}:{timeoutMs:e}}var Gv,de,zv,Vv,Yv,qv,Jo,Jv,Ur,Zv,Qv,eR,Eu=E(()=>{"use strict";xt();nr();M();rt();Dr();st();ut();ym();lt();Fr();cr();$n();Gv={executeWithWorkerFallback:Em,getSessionInitRequestTimeoutMs:qg,isWorkerFallback:_m,consumeWorkerOutageNotice:hm,loadFromFileOnce:z,resolveRuntimeContext:Ge,logServerFallback:ze,holdForServer:Ct,consumeServerOutageNotice:km,shouldTrackProject:ct,readHookEnvironment:()=>process.env},de=Gv,zv=2,Vv=12,Yv=/<private\b[^>]*>[\s\S]*?<\/private\s*>/gi,qv=1e4,Jo=500,Jv=2e3,Ur=class extends Error{constructor(r){super(`session-init did not record the prompt (${r})`);this.reason=r;this.name="SessionPromptNotRecordedError"}reason};Zv=t=>t?t.replace(/\\/g,"/").includes("/.qwen/"):!1,Qv=(t,e=process.env)=>t?e.QWEN_PROJECT_DIR?!0:Zv(t):!1,eR={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&&Vo(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&Y(t.platform)==="codex"&&Am(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()&&Qv(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=Ao(o),u=c.primary,l=Y(t.platform),d=de.loadFromFileOnce(),p=oR(d),g=de.resolveRuntimeContext(),m=Date.now(),h=de.getSessionInitRequestTimeoutMs();if(g.runtime==="server"){let I=tR(g,t,r,l,u,a);try{await rR(g,I,Math.max(Jo,Math.floor(h/zv)));let y=p?await sR(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(yt(y)){de.logServerFallback(y.kind,{status:y.status,message:y.message,route:"/v1/sessions/start",held:!0});let v=Ve(g);de.holdForServer({op:"session_start",request:I},v);let A=de.consumeServerOutageNotice(r,v);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...A?{systemMessage:A,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:A}}:{}}}if(Ke(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(iR(de.readHookEnvironment())){let I=p?await xm(d,a,u,c.allProjects,l,m,h):"";return I?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:I}}:{continue:!0,suppressOutput:!0}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:u});let _=_u(m,h);if(_<Jo){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:_}),e)throw new Ur("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},Nm(l,_));if(de.isWorkerFallback(S)){if(e)throw new Ur("reason"in S?S.reason:"worker_fallback");let I=await de.consumeWorkerOutageNotice(r);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...I?{systemMessage:I}:{}}}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 w=S.sessionDbId,T=S.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:w,promptNumber:T,skipped:S.skipped,contextInjected:S.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${r} | prompt#=${T} | sessionDbId=${w}`),S.skipped&&S.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${w} | promptNumber=${T} | skipped=true | reason=private`,{sessionId:w}),{continue:!0,suppressOutput:!0};let R=p?await xm(d,a,u,c.allProjects,l,m,h):"";return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${w} | promptNumber=${T} | project=${u}`,{sessionId:w}),R?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:R}}:{continue:!0,suppressOutput:!0}}}});var Cm=E(()=>{"use strict";qt();N()});function ri(){return(0,Ye.join)(x(),"state","hook-spool")}function ei(t){if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(Array.isArray(t))return`[${t.map(ei).join(",")}]`;let e=t;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${ei(e[n])}`).join(",")}}`}function pR(t,e){if(t==="summarize"&&e.turnId){let n=e;return(0,Qo.createHash)("sha256").update(ei({contentSessionId:n.contentSessionId,platformSource:Y(n.platformSource),turnId:n.turnId,lastAssistantMessage:n.lastAssistantMessage})).digest("hex")}let r=e.toolUseId;return typeof r=="string"&&Lm.test(r)?`${(0,Qo.createHash)("sha256").update(e.contentSessionId).update("\0").update(Y(e.platformSource)).digest("hex")}-${r}`:(0,Qo.createHash)("sha256").update(t).update("\0").update(e.contentSessionId).update("\0").update(ei(e)).digest("hex")}function Fm(t){return typeof t=="string"&&t.length>0}function Su(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(!cR.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"||!Fm(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=r.kind;return(s==="observation"||s==="file_edit")&&!Fm(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:Y(n.platformSource)},enqueuedAtEpochMs:r.enqueuedAtEpochMs}}function gR(){return yu=Math.max(Date.now(),yu+1),yu}var Qo,re,Ye,cR,uR,Lm,lR,dR,Dm,fR,yu,ti,bu=E(()=>{"use strict";Qo=require("crypto"),re=require("fs"),Ye=require("path");oe();N();ut();M();Cm();cR=["observation","file_edit","summarize","session_end","advisor_calls"],uR=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,Lm=/^[A-Za-z0-9_-]{1,128}$/,lR="corrupt",dR="expired",Dm=10080*60*1e3,fR=300*1e3;yu=0;ti=class{constructor(e=ri()){this.directory=e}directory;get corruptDirectory(){return(0,Ye.join)(this.directory,lR)}get expiredDirectory(){return(0,Ye.join)(this.directory,dR)}enqueue(e,r,n){let s={...r,platformSource:Y(r.platformSource)},o=(0,Ye.join)(this.directory,`${e}-${pR(e,s)}.json`),i=s.toolUseId;if(typeof i=="string"&&Lm.test(i)){let c=(0,Ye.join)(this.directory,`${e}-${i}.json`);try{let u=Su((0,re.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??gR();return $(o,{kind:e,payload:s,enqueuedAtEpochMs:a},{mode:384}),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()-Dm);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,fR,"unknown-session grace window")?a++:i++;continue}if(!h){this.expireIfPastWindow(u,Dm,"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,re.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,re.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,re.renameSync)(e.path,(0,Ye.join)(this.expiredDirectory,e.filename))}catch(i){return i.code==="ENOENT"?!0:(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,re.existsSync)(e))return null;try{let r=Su((0,re.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,Ye.join)(this.directory,e);try{return(0,re.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,re.renameSync)(n,(0,Ye.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:r,corruptDirectory:this.corruptDirectory}),!0}catch(s){return s.code==="ENOENT"?!0:(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,re.existsSync)(this.directory))return{files:[],quarantined:0};let e;try{e=(0,re.readdirSync)(this.directory).filter(s=>uR.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,Ye.join)(this.directory,s),i;try{i=(0,re.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=Su(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 Bm={};Us(Bm,{SPOOL_NUDGE_TIMEOUT_MS:()=>Um,nudgeWorkerToDrainHookSpool:()=>$m,settleHookSpoolNudges:()=>mR,spoolHookEvent:()=>qe});function $m(){if(Bn)return Bn;let t=(async()=>{try{await(await be("/api/spool/nudge",{method:"POST",timeoutMs:Um})).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 Bn=t,wu.add(t),t.finally(()=>{wu.delete(t),Bn===t&&(Bn=null)}),t}async function mR(){await Promise.all([...wu])}function qe(t,e,r){let n=new ti().enqueue(t,e,r);return f.debug("HOOK","Hook event spooled for the worker",{kind:t,entryPath:n}),$m(),n}var Um,wu,Bn,$r=E(()=>{"use strict";bu();xt();M();Um=250,wu=new Set,Bn=null});function jm(t){let e=(t??"").trim();return e?e.slice(0,hR):null}function TR(t){let e=Dt.default.resolve(t);for(let r=0;r<yR;r++){let n=Dt.default.join(e,".git");if((0,ne.existsSync)(n)){try{if((0,ne.statSync)(n).isDirectory())return n;let o=(0,ne.readFileSync)(n,"utf8").match(/^gitdir:\s*(.+)$/m);if(o)return Dt.default.resolve(e,o[1].trim())}catch{return null}return null}let s=Dt.default.dirname(e);if(s===e)return null;e=s}return null}function IR(t){let e=t.trim();if(e.startsWith(Wm))return jm(e.slice(Wm.length));if(bR.test(e))return null}function vR(t){try{return IR((0,ne.readFileSync)(Dt.default.join(t,"HEAD"),"utf8"))}catch{return}}function RR(t){let e=In(t,["rev-parse","--abbrev-ref","HEAD"],SR);return e.status!==0||!e.stdout||e.stdout==="HEAD"?null:jm(e.stdout)}function Tu(t,e){let r;try{r=(0,ne.openSync)(Dt.default.join(t,"logs","HEAD"),"r");let n=(0,ne.fstatSync)(r).size,s=Buffer.alloc(Math.min(n,wR));(0,ne.readSync)(r,s,0,s.length,n-s.length);let o=F.loadFromFile(V,!0,{readOnly:!0}),i=Number(o.MEMINDEX_BRANCH_ACTIVE_DAYS),a=Number.isSafeInteger(i)&&i>0?i:14;for(let c of s.toString("utf8").trimEnd().split(`
24
- `).reverse()){let u=/ (\d+) [+-]\d{4}(?:\t|$)/.exec(c);if(!u)return!1;let l=Number(u[1])*1e3;if(l<=e)return e-l<a*864e5}return!1}catch{return!1}finally{r!==void 0&&(0,ne.closeSync)(r)}}function Hm(t,e=Date.now()){if(!t||!Dt.default.isAbsolute(t))return null;let r=TR(t);if(!r)return null;let n=vR(r);if(n!==void 0)return n&&Tu(r,e)?n:null;let s=ni.get(t);if(s&&e-s.at<_R)return s.branch&&Tu(r,e)?s.branch:null;let o=RR(t);return ni.size>=ER&&ni.clear(),ni.set(t,{at:e,branch:o}),o&&Tu(r,e)?o:null}var ne,Dt,hR,_R,ER,SR,yR,Wm,bR,wR,ni,Xm=E(()=>{"use strict";ne=require("fs"),Dt=_e(require("path"),1);wo();Ie();N();hR=255,_R=5e3,ER=200,SR=1e3,yR=64,Wm="ref: refs/heads/",bR=/^[0-9a-f]{40}([0-9a-f]{24})?$/,wR=8192,ni=new Map});function AR(t=z()){return t.MEMINDEX_BRANCH_MEMORY_ENABLED!=="false"&&t.MEMINDEX_SEND_BRANCH_TO_HOSTING!=="false"}function si(t){if(!AR())return{};let e=Hm(t);return e?{branch:e}:{}}var Iu=E(()=>{"use strict";Xm();st();Ie();N()});function Ft(t,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(t.toLowerCase()):!1}var Wn=E(()=>{"use strict"});function Zm(t,e){return!!t&&!!e}var Qm=E(()=>{"use strict"});function NR(t){return new Set((t??"").split(",").map(e=>e.trim()).filter(Boolean))}function Wr(t,e,r){return Zm(t,e)?r.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&NR(r.MEMINDEX_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:eh:eh}var eh,ii=E(()=>{"use strict";Qm();eh={skip:!1}});var tE,rE=E(()=>{tE=(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 Ht,Ol=E(()=>{Ht="1.10.0"});function BO(t){let e=new Set([t]),r=new Set,n=t.match(nE);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(nE);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 nE,sE,oE=E(()=>{Ol();nE=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;sE=BO(Ht)});function jO(){return Object.defineProperty({},"version",{value:Ht,enumerable:!0,writable:!1,configurable:!1})}function Fe(t,e,r,n=!1){var s;let o=Gi[Ki]=(s=Gi[Ki])!==null&&s!==void 0?s:jO();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${Ht}`);return r.error(i.stack||i.message),!1}return o[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${Ht}.`),!0}function ge(t){let e=Gi[Ki];if(e!=null){if(e!==iE){if(!e.version||!sE(e.version))return;iE=e}return e[t]}}function Le(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Ht}.`);let r=Gi[Ki];r&&delete r[t]}var WO,Ki,Gi,iE,Xt=E(()=>{Ol();oE();WO=Ht.split(".")[0],Ki=Symbol.for(`opentelemetry.js.api.${WO}`),Gi=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function bs(t,e,r){let n=ge("diag");if(n)return n[t](e,...r)}var aE,cE=E(()=>{Xt();aE=class{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return bs("debug",this._namespace,t)}error(...t){return bs("error",this._namespace,t)}info(...t){return bs("info",this._namespace,t)}warn(...t){return bs("warn",this._namespace,t)}verbose(...t){return bs("verbose",this._namespace,t)}}});function uE(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 lE=E(()=>{});var HO,J,Kt=E(()=>{Xt();cE();lE();HO="diag",J=class dE{static instance(){return this._instance||(this._instance=new dE),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=uE((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 Fe("diag",u,r,!0)};r.setLogger=n,r.disable=()=>{Le(HO,r)},r.createComponentLogger=s=>new aE(s),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}}});var fE,pE=E(()=>{fE=class ws{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 ws(this._entries);return n._entries.set(e,r),n}removeEntry(e){let r=new ws(this._entries);return r._entries.delete(e),r}removeEntries(...e){let r=new ws(this._entries);for(let n of e)r._entries.delete(n);return r}clear(){return new ws}}});var gE,mE=E(()=>{gE=Symbol("BaggageEntryMetadata")});function hE(t={}){return new fE(new Map(Object.entries(t)))}function _E(t){return typeof t!="string"&&(XO.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:gE,toString(){return t}}}var XO,Pl=E(()=>{Kt();pE();mE();XO=J.instance()});function tn(t){return Symbol.for(t)}var zi,Ts=E(()=>{zi=new class kl{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 kl(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=n=>{let s=new kl(r._currentContext);return s._currentContext.delete(n),s}}}});var xl,Nl,EE,SE=E(()=>{xl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],Nl={};if(typeof console<"u")for(let t of["error","warn","info","debug","trace","log"])typeof console[t]=="function"&&(Nl[t]=console[t]);EE=class{constructor(){function t(e){return function(...r){let n=Nl[e];if(typeof n!="function"&&(n=Nl.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<xl.length;e++)this[xl[e].n]=t(xl[e].c)}}});function yE(){return Dl}var KO,Vi,GO,zO,VO,YO,Cl,qO,JO,ZO,Dl,QO,eP,tP,rP,nP,sP,oP,Fl=E(()=>{KO=class{constructor(){}createGauge(t,e){return eP}createHistogram(t,e){return tP}createCounter(t,e){return QO}createUpDownCounter(t,e){return rP}createObservableGauge(t,e){return sP}createObservableCounter(t,e){return nP}createObservableUpDownCounter(t,e){return oP}addBatchObservableCallback(t,e){}removeBatchObservableCallback(t){}},Vi=class{},GO=class extends Vi{add(t,e){}},zO=class extends Vi{add(t,e){}},VO=class extends Vi{record(t,e){}},YO=class extends Vi{record(t,e){}},Cl=class{addCallback(t){}removeCallback(t){}},qO=class extends Cl{},JO=class extends Cl{},ZO=class extends Cl{},Dl=new KO,QO=new GO,eP=new VO,tP=new YO,rP=new zO,nP=new qO,sP=new JO,oP=new ZO});var bE,wE=E(()=>{bE=(function(t){return t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE",t})({})});function TE(){return Ul}var Ll,Ul,Yi=E(()=>{Ll=class{emit(t){}enabled(){return!1}},Ul=new Ll});var IE,vE=E(()=>{IE=(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 qi,Ji,$l=E(()=>{qi={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},Ji={set(t,e,r){t!=null&&(t[e]=r)}}});var RE,AE=E(()=>{RE=(function(t){return t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED",t})({})});var Bl,Wl,Zi,jl=E(()=>{Bl="0000000000000000",Wl="00000000000000000000000000000000",Zi={traceId:Wl,spanId:Bl,traceFlags:0}});var Gt,Qi=E(()=>{jl();Gt=class{constructor(t=Zi){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 ME(t,e){if(typeof t!="string"||t.length!==e)return!1;let r=0;for(let n=0;n<t.length;n+=4)r+=(ea[t.charCodeAt(n)]|0)+(ea[t.charCodeAt(n+1)]|0)+(ea[t.charCodeAt(n+2)]|0)+(ea[t.charCodeAt(n+3)]|0);return r===e}function Hl(t){return ME(t,32)&&t!=="00000000000000000000000000000000"}function Xl(t){return ME(t,16)&&t!=="0000000000000000"}function rn(t){return Hl(t.traceId)&&Xl(t.spanId)}function OE(t){return new Gt(t)}var ea,ta=E(()=>{Qi();ea=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 PE,kE=E(()=>{Ts();PE=class{active(){return zi}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 Kl,iP,aP,zt,Is=E(()=>{Xt();Kt();kE();Kl="context",iP=new PE,aP=Object.freeze({dispose:()=>{}}),zt=class xE{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new xE),this._instance}setGlobalContextManager(e){return Fe(Kl,e,J.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,J.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.")),aP)}_getContextManager(){return ge(Kl)||iP}disable(){this._getContextManager().disable(),Le(Kl,J.instance())}}});function ra(t){return t.getValue(Gl)||void 0}function NE(){return ra(zt.getInstance().active())}function vs(t,e){return t.setValue(Gl,e)}function CE(t){return t.deleteValue(Gl)}function DE(t,e){return vs(t,new Gt(e))}function na(t){var e;return(e=ra(t))===null||e===void 0?void 0:e.spanContext()}var Gl,zl=E(()=>{Ts();Is();Qi();Gl=tn("OpenTelemetry Context Key SPAN")});function cP(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 Vl,sa,Yl=E(()=>{Is();Qi();zl();ta();Vl=zt.getInstance(),sa=class{startSpan(t,e,r=Vl.active()){if(e?.root)return new Gt;let n=r&&na(r);return cP(n)&&rn(n)?new Gt(n):new Gt}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:Vl.active(),u=this.startSpan(t,o,c),l=vs(c,u);return Vl.with(l,a,void 0,u)}}});var uP,oa,ql=E(()=>{Yl();uP=new sa,oa=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):uP}}});var FE,LE=E(()=>{FE=(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 UE,$E=E(()=>{UE=(function(t){return t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR",t})({})});function BE(t){return lP.test(t)}function WE(t){return dP.test(t)&&!fP.test(t)}var Jl,lP,dP,fP,jE=E(()=>{Jl="[_0-9a-z-*/]",lP=new RegExp(`^(?:${`[a-z]${Jl}{0,255}`}|${`[a-z0-9]${Jl}{0,240}@[a-z]${Jl}{0,13}`})$`),dP=/^[ -~]{0,255}[!-~]$/,fP=/,|=/});var Zl,HE,XE,KE,GE,VE=E(()=>{jE();Zl=32,HE=512,XE=",",KE="=",GE=class zE{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>=Zl)return this;s+=e.length+r.length+(this._internalState.size>0?2:1)}if(s>HE)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+KE+this.get(r)),e),[]).join(XE)}_parse(e){e.length>HE||(this._internalState=e.split(XE).reduceRight((r,n)=>{let s=n.trim(),o=s.indexOf(KE);if(o!==-1){let i=s.slice(0,o),a=s.slice(o+1,n.length);BE(i)&&WE(a)&&r.set(i,a)}return r},new Map),this._internalState.size>Zl&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Zl))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new zE;return e._internalState=new Map(this._internalState),e}}});function YE(t){return new GE(t)}var qE=E(()=>{VE()});var JE,ZE=E(()=>{Yl();JE=class{getTracer(t,e,r){return new sa}}});var pP,Rs,Ql=E(()=>{ql();ZE();pP=new JE,Rs=class{getTracer(t,e,r){var n;return(n=this.getDelegateTracer(t,e,r))!==null&&n!==void 0?n:new oa(this,t,e,r)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:pP}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 QE,eS=E(()=>{QE=(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 ed,tS=E(()=>{Is();ed=zt.getInstance()});var td,rS=E(()=>{Kt();td=J.instance()});var gP,nS,sS=E(()=>{Yi();gP=class{getLogger(t,e,r){return new Ll}},nS=new gP});var oS,iS=E(()=>{Yi();oS=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):Ul}}});var rd,aS=E(()=>{sS();iS();rd=class{getLogger(t,e,r){var n;return(n=this._getDelegateLogger(t,e,r))!==null&&n!==void 0?n:new oS(this,t,e,r)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:nS}_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 nd,cS,lS=E(()=>{Xt();Kt();aS();nd="logs",cS=class uS{constructor(){this._proxyLoggerProvider=new rd}static getInstance(){return this._instance||(this._instance=new uS),this._instance}setGlobalLoggerProvider(e){let r=Fe(nd,e,J.instance());return r&&this._proxyLoggerProvider._setDelegate(e),r}getLoggerProvider(){return ge(nd)||this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){Le(nd,J.instance()),this._proxyLoggerProvider=new rd}}});var sd,dS=E(()=>{lS();sd=cS.getInstance()});var mP,fS,pS=E(()=>{Fl();mP=class{getMeter(t,e,r){return Dl}},fS=new mP});var od,gS,hS=E(()=>{Xt();Kt();pS();od="metrics",gS=class mS{constructor(){}static getInstance(){return this._instance||(this._instance=new mS),this._instance}setGlobalMeterProvider(e){return Fe(od,e,J.instance())}getMeterProvider(){return ge(od)||fS}getMeter(e,r,n){return this.getMeterProvider().getMeter(e,r,n)}disable(){Le(od,J.instance())}}});var id,_S=E(()=>{hS();id=gS.getInstance()});var ES,SS=E(()=>{ES=class{inject(t,e){}extract(t,e){return t}fields(){return[]}}});function cd(t){return t.getValue(ad)||void 0}function yS(){return cd(zt.getInstance().active())}function bS(t,e){return t.setValue(ad,e)}function wS(t){return t.deleteValue(ad)}var ad,TS=E(()=>{Ts();Is();ad=tn("OpenTelemetry Baggage Key")});var ud,hP,IS,RS=E(()=>{Xt();Kt();Pl();$l();SS();TS();ud="propagation",hP=new ES,IS=class vS{constructor(){this.createBaggage=hE,this.getBaggage=cd,this.getActiveBaggage=yS,this.setBaggage=bS,this.deleteBaggage=wS}static getInstance(){return this._instance||(this._instance=new vS),this._instance}setGlobalPropagator(e){return Fe(ud,e,J.instance())}inject(e,r,n=Ji){return this._getGlobalPropagator().inject(e,r,n)}extract(e,r,n=qi){return this._getGlobalPropagator().extract(e,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){Le(ud,J.instance())}_getGlobalPropagator(){return ge(ud)||hP}}});var ld,AS=E(()=>{RS();ld=IS.getInstance()});var dd,MS,PS=E(()=>{Xt();Kt();zl();ta();Ql();dd="trace",MS=class OS{constructor(){this._proxyTracerProvider=new Rs,this.wrapSpanContext=OE,this.isSpanContextValid=rn,this.deleteSpan=CE,this.getSpan=ra,this.getActiveSpan=NE,this.getSpanContext=na,this.setSpan=vs,this.setSpanContext=DE}static getInstance(){return this._instance||(this._instance=new OS),this._instance}setGlobalTracerProvider(e){let r=Fe(dd,this._proxyTracerProvider,J.instance());return r&&this._proxyTracerProvider.setDelegate(e),r}getTracerProvider(){return ge(dd)||this._proxyTracerProvider}getTracer(e,r){return this.getTracerProvider().getTracer(e,r)}disable(){Le(dd,J.instance()),this._proxyTracerProvider=new Rs}}});var fd,kS=E(()=>{PS();fd=MS.getInstance()});var xS={};Us(xS,{DiagConsoleLogger:()=>EE,DiagLogLevel:()=>tE,INVALID_SPANID:()=>Bl,INVALID_SPAN_CONTEXT:()=>Zi,INVALID_TRACEID:()=>Wl,ProxyTracer:()=>oa,ProxyTracerProvider:()=>Rs,ROOT_CONTEXT:()=>zi,SamplingDecision:()=>QE,SeverityNumber:()=>IE,SpanKind:()=>FE,SpanStatusCode:()=>UE,TraceFlags:()=>RE,ValueType:()=>bE,baggageEntryMetadataFromString:()=>_E,context:()=>ed,createContextKey:()=>tn,createNoopLogger:()=>TE,createNoopMeter:()=>yE,createTraceState:()=>YE,default:()=>_P,defaultTextMapGetter:()=>qi,defaultTextMapSetter:()=>Ji,diag:()=>td,isSpanContextValid:()=>rn,isValidSpanId:()=>Xl,isValidTraceId:()=>Hl,logs:()=>sd,metrics:()=>id,propagation:()=>ld,trace:()=>fd});var _P,NS=E(()=>{rE();Pl();Ts();SE();Fl();wE();Yi();vE();$l();AE();jl();ta();ql();LE();$E();qE();Ql();eS();tS();rS();dS();_S();AS();kS();_P={context:ed,diag:td,logs:sd,metrics:id,propagation:ld,trace:fd}});function ty(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 sn(t){if(!t)return!1;if(t.startsWith("memory_")||t==="mem_search"||t==="get_summaries")return!0;let e=ty(t);return e!==null&&dk.has(e)}function _a(t){return t==="save_memory"||ty(t)==="save_memory"}var dk,Ea=E(()=>{"use strict";dk=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 Td(t){return typeof t=="string"&&t.length>0}var Cs,Sy=E(()=>{"use strict";Cs=class extends Error{constructor(r){super(`adapter rejected input: ${r}`);this.reason=r;this.name="AdapterRejectedInput"}reason}});var Pk,yy,Id,kk,xk,by,wy=E(()=>{"use strict";Sy();nr();Pk=128,yy=t=>typeof t=="string"&&t.length>0&&t.length<=Pk?t:void 0,Id=t=>typeof t=="string"?t:void 0,kk=t=>t.hook_event_name==="PostToolUseFailure"?{error:t.error,is_interrupt:t.is_interrupt===!0}:void 0,xk=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},by={normalizeInput(t){let e=t??{},r=e.cwd??process.cwd();if(!Td(r))throw new Cs("invalid_cwd");let n=Cp(r);if(!Td(n))throw new Cs("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:xk(e),toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response??kk(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:yy(e.agent_id),agentType:yy(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 Ty(t,e){return qe("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 Iy,vy=E(()=>{"use strict";$r();M();rt();Dr();ii();st();Iu();Wn();ut();Fr();cr();$n();Ea();Iy={async execute(t){let{sessionId:e,cwd:r,toolName:n,toolInput:s,toolResponse:o}=t,i=Y(t.platform);if(!n)return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(sn(n))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(f.dataIn("HOOK",`PostToolUse: ${n}`,{}),!r)throw new Error(`Missing cwd in PostToolUse hook input for session ${e}, tool ${n}`);if(!ct(r))return f.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:r,toolName:n}),{continue:!0,suppressOutput:!0};let a=Wr(t.agentId,t.agentType,z());if(a.skip)return f.debug("HOOK",`Skipping observation: ${a.reason}`,{toolName:n,agentId:t.agentId,agentType:t.agentType}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(_a(n))return Ty(t,i);let c=Ge();if(c.runtime==="server"){if(Ft(n,z().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 u={projectId:c.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},...si(r)};try{return await c.client.recordEvent(u),f.debug("HOOK","Observation sent successfully via server",{toolName:n}),await Lr(c.client,Ve(c)),{continue:!0,suppressOutput:!0}}catch(l){if(yt(l))return ze(l.kind,{status:l.status,message:l.message,route:"/v1/events",held:!0}),Ct({op:"event",request:u},Ve(c)),{continue:!0,suppressOutput:!0};if(Ke(l)&&l.isFallbackEligible())ze(l.kind,{status:l.status,message:l.message,route:"/v1/events"});else return f.error("HOOK","Server event failed (non-recoverable)",{error:l instanceof Error?l.message:String(l)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}return Ty(t,i)}}});function Dk(t,e,r){let n=0;for(;n<e.length;){let s=(0,Qe.readSync)(t,e,n,e.length-n,r+n);if(s===0)break;n+=s}return n}function*Fk(t,e){let r=Math.max(1,e.maxChunkBytes??Ry),n=Math.min(r,Math.max(1,e.initialBytes??Nk)),s=(0,Qe.openSync)(t,"r");try{let o=(0,Qe.fstatSync)(s).size,i=Buffer.alloc(0);for(;o>0;){let a=Math.max(0,o-n),c=Buffer.alloc(o-a),u=Dk(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,Qe.closeSync)(s)}}function Ay(t,e,r={}){if(!t||!(0,Qe.existsSync)(t)){f.warn("PARSER",`Transcript path missing or file does not exist: ${t}`);return}let n=!1;for(let s of Fk(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*vd(t){let e=t.split(`
25
- `);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 Lk(t,e,r,n,s){let o,i=null,a,c,u=!1,l=0,d=Math.max(0,s?.modelSearchBudgetBytes??Ck),p=Ay(t,(g,m,h)=>{if(s?.includeTurnId&&!u)for(let w of vd(g)){if(w.type!=="assistant"&&w.message?.role!=="assistant")continue;u=!0;let T=w.uuid??w.message?.id;typeof T=="string"&&T&&(c=T);break}if(o!==void 0&&(l+=h),n&&a===void 0&&(a=Py(g)),o===void 0){let w=Hk(g,e,r);w.kind==="text"?o=w.text:w.kind!=="none"&&i===null&&(i=w.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 Rd(t,e=!1,r){let n=Lk(t,"assistant",e,!0,r);return{text:n.text,...n.model===void 0?{}:{model:n.model},...n.turnId===void 0?{}:{turnId:n.turnId}}}function My(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(`
26
- `):null}function Bk(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 Wk(t,e){if(e==="user"&&t?.type==="context.append_message")return My(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 jk(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 Hk(t,e,r){let n=!1,s=null,o="blank";for(let i of vd(t)){let a=Bk(i),c=typeof i.type=="string"?Uk[i.type]:void 0,u=typeof i.type=="string"?$k[i.type]:void 0;if((a??c??u??i.type??i.role)!==e)continue;n=!0;let d,p;if(a!==void 0)d=Wk(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=My(p);if(g===null)continue;d=g}if(r&&(d=zo(d),d=d.replace(/\n{3,}/g,`
15
+ `)}debug(e,r,n,s){this.log(0,e,r,n,s)}info(e,r,n,s){this.log(1,e,r,n,s)}warn(e,r,n,s){this.log(2,e,r,n,s)}setErrorSink(e){$a=e}error(e,r,n,s){this.log(3,e,r,n,s),this.routeErrorToSink(r,n,s)}routeErrorToSink(e,r,n){try{if(!$a||!(n instanceof Error))return;$a(n)}catch{}}dataIn(e,r,n,s){this.info(e,`\u2192 ${r}`,n,s)}dataOut(e,r,n,s){this.info(e,`\u2190 ${r}`,n,s)}success(e,r,n,s){this.info(e,`\u2713 ${r}`,n,s)}failure(e,r,n,s){this.error(e,`\u2717 ${r}`,n,s)}},f=new Wa});function uf(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var lf=E(()=>{"use strict";M()});function Zt(t){let e=(0,Se.resolve)(t),r=[],n=e;for(;;)try{return(0,Se.join)(df.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 tw(t,e){return Zt(t)===Zt(e)}function rw(t,e){let r=Zt(e);return t===r||t.startsWith(r.endsWith(Se.sep)?r:r+Se.sep)}function nw(t,e=(0,_t.homedir)()){let r=Zt(t),n=Zt(e);return(process.platform==="win32"?[(0,_t.tmpdir)()]:[(0,_t.tmpdir)(),...ew]).some(o=>Zt(o)!==n&&rw(r,o))}function pn(t=process.env,e=(0,_t.homedir)()){return t.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:nw(un(t,e),e)}function gf(t){return(0,Ha.createHash)("sha256").update(Se.win32.resolve(t).toLowerCase()).digest().readUInt32BE(0)%sw}function ja(t=process.platform,e=(0,_t.homedir)()){return t==="win32"?pf+gf(e):38700+(process.getuid?.()??77)%100}function Xa(t=process.platform,e=(0,_t.homedir)()){return t==="win32"?pf+ow+gf(e):38877+(process.getuid?.()??77)%100}function Ka(t){let e=(0,Ha.createHash)("sha256").update(Zt(t)).digest();return Zb+e.readUInt32BE(0)%Qb}function mf(t=process.env,e=(0,_t.homedir)()){return pn(t,e)?Ka(un(t,e)):ja(process.platform,e)}function hf(t,e){return typeof t!="string"||t.length===0?"unknown":tw(t,e)?"same":"foreign"}var Ha,df,_t,Se,Zb,Qb,ew,ff,pf,sw,ow,Ga=E(()=>{"use strict";Ha=require("crypto"),df=require("fs"),_t=require("os"),Se=require("path");Ca();Zb=4e4,Qb=9e3,ew=["/tmp","/private/tmp","/var/folders","/private/var/folders"],ff="60";pf=39e3,sw=500,ow=500});function _f(t){return typeof t=="boolean"?String(t):t}function aw(t){let e=t.MEMINDEX_OPENROUTER_MODEL;if(typeof e!="string"||!iw.has(e.trim()))return!1;let r=typeof t.MEMINDEX_OPENROUTER_BASE_URL=="string"?t.MEMINDEX_OPENROUTER_BASE_URL.trim():"";return r===""||uf(r)}function bf(t,e){return(0,At.join)((0,At.dirname)(t),`.${(0,At.basename)(t)}.${e.markerTag}`)}function za(t,e){try{(0,Qt.writeFileSync)(bf(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Qt,At,gn,iw,Ef,Sf,yf,F,Ie=E(()=>{"use strict";Qt=require("fs"),At=require("path"),gn=require("os");rt();oe();lf();cn();Hs();Ga();iw=new Set(["xiaomi/mimo-v2-flash:free"]);Ef=18e4,Sf=[{key:"MEMINDEX_OBSERVER_MAX_CONVERSATION_CHARS",legacy:"400000",markerTag:"observer-conversation-budget-migrated-v1"},{key:"MEMINDEX_REDACT_ENABLED",legacy:"false",markerTag:"redaction-default-migrated-v1"},{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"}];yf=new Set,F=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_CONTEXT_PROJECTS:"current",MEMINDEX_WORKER_PORT:String(mf()),MEMINDEX_WORKER_HOST:"127.0.0.1",MEMINDEX_WORKER_HEARTBEAT_STALE_MS:"120000",MEMINDEX_ALLOWED_ORIGINS:"",MEMINDEX_PUBLIC_URL:"",MEMINDEX_API_TIMEOUT_MS:String(Rt(ie.API_REQUEST)),MEMINDEX_SESSION_INIT_TIMEOUT_MS:String(ln()),MEMINDEX_IDLE_EXIT_SEC:pn()?ff:"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,At.join)((0,gn.homedir)(),".memindex"),MEMINDEX_SNAPSHOT_ENABLED:"true",MEMINDEX_SNAPSHOT_INTERVAL_HOURS:"24",MEMINDEX_SNAPSHOT_KEEP:"7",MEMINDEX_LOG_LEVEL:"INFO",MEMINDEX_LOG_RETENTION_DAYS:"30",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_BRANCH_ACTIVE_DAYS:"14",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,At.join)((0,gn.homedir)(),".memindex","transcript-watch.json"),MEMINDEX_CODEX_TRANSCRIPT_INGESTION:"false",MEMINDEX_CODEX_SUBAGENT_INGESTION:"false",MEMINDEX_MAX_CONCURRENT_AGENTS:"2",MEMINDEX_SKILLS_DISABLED:"",MEMINDEX_OBSERVER_MAX_CONVERSATION_CHARS:"100000",MEMINDEX_OBSERVER_CONTEXT_WINDOW:"",MEMINDEX_OBSERVER_MAX_OUTPUT_TOKENS:"4096",MEMINDEX_OBSERVE_BARE_PROMPTS:"false",MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD:"3",MEMINDEX_REDACT_ENABLED:"true",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,gn.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(Ef),MEMINDEX_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS:String(Ef),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(Xa())}`,MEMINDEX_SERVER_API_KEY:"",MEMINDEX_SERVER_PROJECT_ID:"",MEMINDEX_SERVER_BETA_URL:`http://127.0.0.1:${process.env.MEMINDEX_SERVER_PORT??String(Xa())}`,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,Qt.existsSync)(e)){let p=this.getAllDefaults();if(!n.readOnly)try{$(e,p,{mode:384});for(let g of Sf)za(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,Qt.readFileSync)(e,"utf-8"),o=Jt(s),i=br(o),a=i!==o,c=Bs(i),u=Kd(o),l=a&&Object.keys(u).some(p=>p!=="env");if(a&&!l&&!n.readOnly)try{$(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(aw(c)){let p=String(c.MEMINDEX_OPENROUTER_MODEL).trim();if(c={...c,MEMINDEX_OPENROUTER_MODEL:this.DEFAULTS.MEMINDEX_OPENROUTER_MODEL},!n.readOnly)try{$(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 Sf)if(!(0,Qt.existsSync)(bf(e,p))){if(_f(c[p.key])!==p.legacy){n.readOnly||za(e,p);continue}if(c={...c,[p.key]:this.DEFAULTS[p.key]},!n.readOnly)try{$(e,l?{...u,env:c}:c,{mode:384}),za(e,p);let g=p.key.endsWith("_MS")?"ms":"";console.warn(`[SETTINGS] Migrated ${p.key} off the old ${p.legacy}${g} default to ${this.DEFAULTS[p.key]}${g}:`,e)}catch(g){let m=`${p.key}\0${e}`;yf.has(m)||(yf.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]=_f(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 Nf(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Ja,qs=E(()=>{"use strict";Ja="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 Zs(t=x()){let e=(0,j.openSync)((0,Js.join)(t,Df),j.constants.O_RDONLY|(j.constants.O_NOFOLLOW??0));try{let r=(0,j.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,j.readFileSync)(e,"utf8");if(!hw.test(n))throw new Error("Invalid worker secret");return n}finally{(0,j.closeSync)(e)}}function Lf(t=x()){(0,j.mkdirSync)(t,{recursive:!0,mode:448});let e=(0,Js.join)(t,Df);try{return Zs(t)}catch(s){if(s.code!=="ENOENT")throw s}let r=(0,Js.join)(t,`.worker-secret-${(0,Mt.randomBytes)(16).toString("hex")}`),n=(0,j.openSync)(r,"wx",384);try{(0,j.fchmodSync)(n,384),(0,j.writeFileSync)(n,(0,Mt.randomBytes)(32).toString("hex")),(0,j.fsyncSync)(n)}finally{(0,j.closeSync)(n)}try{try{(0,j.linkSync)(r,e)}catch(s){if(s.code!=="EEXIST")throw s}}finally{(0,j.unlinkSync)(r)}return Zs(t)}function _n(t,e=x()){let r=(t.method??"GET").toUpperCase(),n=r==="GET"||r==="HEAD",s=new Headers(t.headers);if(n)try{s.set(Cf,Zs(e))}catch{return t}else s.set(Cf,Lf(e));return{...t,headers:s,redirect:"error"}}function Za(){return(0,Mt.randomBytes)(32).toString("hex")}function yw(t){return typeof t=="string"&&Ff.test(t)}function bw(t,e){return(0,Mt.createHmac)("sha256",t).update(_w+e).digest("hex")}function Qa(t,e,r=x()){if(typeof t!="string"||!Ff.test(t)||!yw(e))return!1;let n;try{n=Zs(r)}catch{return!1}let s=Buffer.from(bw(n,e)),o=Buffer.from(t);return o.length===s.length&&(0,Mt.timingSafeEqual)(o,s)}function Uf(t){try{return new URL(t).origin}catch{return null}}function tc(t,e=x(),r=Date.now()){let n=Uf(t);n!==null&&ec.set(n,{dataDir:e,at:r})}function $f(){ec.clear()}function ww(t,e=x(),r=Date.now()){let n=Uf(t),s=n===null?void 0:ec.get(n);return s!==void 0&&s.dataDir===e&&r-s.at<Sw}function rc(t,e){let r=new URL("/api/health",t);return r.searchParams.set(Ew,e),r.toString()}async function Qs(t,e={}){let r=e.dataDir??x();if(!e.fresh&&ww(t,r))return!0;let n=Za(),o=await(e.fetchImpl??((c,u)=>fetch(c,u)))(rc(t,n),{method:"GET",redirect:"error",signal:e.signal?AbortSignal.any([e.signal,AbortSignal.timeout(Math.max(1,e.timeoutMs??2e3))]):AbortSignal.timeout(Math.max(1,e.timeoutMs??2e3))}),i=null;try{i=await o.json()}catch{}let a=typeof i=="object"&&i!==null?i.proof:void 0;return Qa(a,n,r)?(tc(t,r),!0):!1}var Mt,j,Js,Cf,Df,hw,Ff,_w,Ew,Sw,Rr,ec,nc=E(()=>{"use strict";Mt=require("node:crypto"),j=require("node:fs"),Js=require("node:path");N();qs();Cf="X-Memindex-Secret",Df="worker-secret",hw=/^[a-f0-9]{64}$/,Ff=/^[a-f0-9]{64}$/,_w="memindex-worker-identity:",Ew="challenge",Sw=1e3,Rr=class extends Error{constructor(e){super(e),this.name="WorkerIdentityError"}};ec=new Map});async function*Iw(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 vw(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*Hf(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 sc(r)},g=m=>{if(m.length===0){let v=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,v}if(m[0]===Tw)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 Iw(t)){let h=0;for(let _=0;_<m.length;_++){let S=m[_];if(i&&(i=!1,S===Wf)){h=_+1;continue}if(S!==Bf&&S!==Wf)continue;s.push(m.subarray(h,_));let b=vw(s,o+(_-h));s=[],o=0;let w=g(b);w&&(e.terminalEventNames?.includes(w.event)&&(d=!0),yield w),i=S===Bf,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 oc(e.terminalEventNames)}var sc,oc,Bf,Wf,Tw,jf=E(()=>{"use strict";sc=class extends Error{constructor(r){super(`SSE event exceeded ${r} bytes`);this.maxEventBytes=r;this.name="SseEventTooLargeError"}maxEventBytes},oc=class extends Error{constructor(r){super(`SSE stream ended before a terminal event (${r.join(", ")})`);this.terminalEventNames=r;this.name="StreamEndedEarlyError"}terminalEventNames},Bf=13,Wf=10,Tw=58});function z(){return eo!==null||(eo=F.loadFromFile(V)),eo}var eo,st=E(()=>{"use strict";Ie();N();eo=null});function to(t){return(t.MEMINDEX_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var Xf=E(()=>{"use strict"});var Kf=E(()=>{"use strict"});function ic(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var ac=E(()=>{"use strict"});function uc(t,e,r){return(0,cc.spawn)(t,e??[],{...r,windowsHide:!0})}var cc,Rw,Aw,oN,lc=E(()=>{"use strict";cc=require("node:child_process");Rw=new Set([".cmd",".bat"]),Aw=new Set([".exe",".com"]),oN=new Set([...Aw,...Rw])});function He(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(kw.has(r)){e[r]=n;continue}Ow.has(r)||Mw.some(s=>r.startsWith(s))||(e[r]=n)}return e}var Mw,Ow,Pw,kw,En=E(()=>{"use strict";Mw=["CLAUDECODE_","CLAUDE_CODE_"],Ow=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Pw=new Set(["NODE_USE_ENV_PROXY","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"]),kw=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",...Pw])});function no(t){return`${dc}${t}`}function pc(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 Nw(t){fc+=1;let e=(0,ro.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:{...He(process.env),LC_ALL:"C",LANG:"C",TZ:"UTC"}});return pc("powershell-cim",t,e)}function Cw(t,e=!1){if(!e){let n=Gf.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<xw))return n.token}let r=null;try{r=Nw(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)&&Gf.set(t,{token:r,capturedAtMs:Date.now()}),r}function Vf(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){fc+=1;try{let r=(0,zf.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 Cw(t,e);fc+=1;try{let r=(0,ro.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...He(process.env),LC_ALL:"C",LANG:"C",TZ:"UTC"}}),n=pc("ps-lstart",t,r);return n===null?null:no(n)}catch(r){return f.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Et(t){return Vf(t,!1)}function Dw(t,e){let r=Vf(t,!0);if(r===null||!r.startsWith(dc)||e.startsWith(dc))return r;try{let n=(0,ro.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...He(process.env),LC_ALL:"C",LANG:"C"}});return pc("ps-lstart",t,n)}catch{return null}}function Re(t,e){if(e===null)return!0;let r=Dw(t,e);return r===null?!0:r===e}var ro,zf,dc,xw,Gf,fc,so=E(()=>{"use strict";ro=require("child_process"),zf=require("fs");M();En();dc="utc:";xw=5e3,Gf=new Map,fc=0});async function Ae(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Et(t),s=()=>Re(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 gc("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===Fw||Lw.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new oo(t,`taskkill failed for PID ${t} (exit ${String(i)}): ${a.trim()||c}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",i=await io(t);for(let u of i){if(!Re(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 io(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(!Re(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 oo(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function Uw(){return process.platform==="win32"?Ww():process.platform==="linux"?$w():Bw()}function $w(){let t=[],e;try{e=(0,ao.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,ao.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 Bw(){let t;try{t=(await gc("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C",TZ:"UTC"}})).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?no(s):null})}return e}async function Ww(){let t;try{t=(await gc("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 io(t){let e=await Uw(),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 Yf,ao,qf,gc,Fw,Lw,oo,Ar=E(()=>{"use strict";Yf=require("child_process"),ao=require("fs"),qf=require("util");M();so();gc=(0,qf.promisify)(Yf.execFile),Fw=128,Lw=/not found|no running instance|no tasks/i,oo=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 co(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 Zf(t){if(!t||!q(t.pid))return!1;if(!t.startToken)return!0;let e=Re(t.pid,t.startToken);return e||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken}),e}function uo(t,e=zw){if(!Zf(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=>Jf.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 ot(t=B.workerPid()){if(!(0,tr.existsSync)(t))return null;let e;try{e=JSON.parse((0,tr.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&uo(e)?e:null}function lo(){return mc||(mc=new _c),mc}function hc(){let t=Vw.shift();t&&t.notify()}var tr,Jf,jw,Xw,Kw,Gw,zw,_c,mc,vN,Vw,it=E(()=>{"use strict";lc();tr=require("fs"),Jf=_e(require("path"),1);M();oe();En();N();so();Ar();jw=5e3,Xw=1e3,Kw=B.supervisorRegistry(),Gw=null;zw={platform:process.platform,readCommandLine:t=>(0,tr.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};_c=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Kw){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,tr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,tr.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"&&hc())}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)hc();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,Et(a.pid)]));for(let a of s)try{process.platform==="win32"?await Ae(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 co(s,jw);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(!Re(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 Ae(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()+Xw;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"&&hc();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{$(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{Gw?.({errorCategory:r.code??"unknown"})}catch{}}},mc=null;vN=180*1e3,Vw=[]});async function ep(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Yw,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,Et(c.pid)),o.set(c.id,await io(c.pid));try{await Qf(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 co(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=Re(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 Qf(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{qw(o.get(c.id)??[],c.pid)}}await co(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);tp(r,e),t.registry.pruneDeadEntries()}function tp(t,e,r=!1){if(!(0,Mr.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,Mr.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,Mr.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 qw(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!q(r))){if(!Re(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 Qf(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 Ae(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await Ae(r)}var Mr,Yw,Ec=E(()=>{"use strict";Mr=require("fs");M();it();N();Ar();Yw=B.workerPid()});function Jw(){let e=lo().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function np(){Or===null&&(Or=setInterval(Jw,rp),Or.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:rp}))}function sp(){Or!==null&&(clearInterval(Or),Or=null,f.debug("SYSTEM","Health checker stopped"))}var rp,Or,op=E(()=>{"use strict";M();it();rp=3e4,Or=null});function eT(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 tT(){let t=await Zw("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return eT(t.stdout)}function rT(t,e){let r=t.filter(i=>Qw.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 cp(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??tT,s=t.isAlive??q,o=t.killTree??(g=>Ae(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}=rT(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 ip,ap,Zw,Qw,up=E(()=>{"use strict";ip=require("child_process"),ap=require("util");M();Ar();it();Zw=(0,ap.promisify)(ip.execFile),Qw=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function lp(t={}){let e=t.pidFilePath??nT;if(!(0,rr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,rr.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,rr.rmSync)(e,{force:!0}),"invalid"}return uo(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,rr.rmSync)(e,{force:!0})),"stale")}var rr,nT,Sc,KN,Sn=E(()=>{"use strict";rr=require("fs");M();it();Ec();op();up();N();it();nT=B.workerPid(),Sc=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(),lp({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,cp({registry:this.registry}).catch(r=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),np()}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}sp(),this.stopPromise=ep({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}},KN=new Sc(lo())});function dp(t,e){if(!(0,fo.existsSync)(t))return e;try{return Jt((0,fo.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var fo,fp=E(()=>{"use strict";fo=require("fs");oe()});function sT(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function oT(t,e){if(sT(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 go(t,e){return oT(t,e).enabled}function mp(t){let e=t.MEMINDEX_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function iT(){return(0,yc.join)(x(),gp)}function yn(){let t;try{t=dp(iT(),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 aT(t){let e=x();(0,po.mkdirSync)(e,{recursive:!0}),(0,po.writeFileSync)((0,yc.join)(e,gp),JSON.stringify(t,null,2)+`
19
+ `)}function mo(){let t=yn();if(t?.installId)return t.installId;let e=(0,pp.randomUUID)();return aT({installId:e,decidedAt:""}),e}var yc,po,pp,gp,bc=E(()=>{"use strict";yc=require("path"),po=require("fs"),pp=require("crypto");N();fp();M();gp="telemetry.json"});function Sp(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>_p?e.slice(0,_p):e}catch{return""}}function wc(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Ep.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 Tc(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 cT(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${Me}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Me}@`))}function uT(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function lT(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)}${Me}`})}function dT(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,Me),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Me),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Me),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Me),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Me),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Me),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,Me),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Me),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,Me),e}function fT(t){return typeof t!="string"||t.length===0?t??"":t.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
20
+ `).trim()}function Ic(t){let e=Sp(t);return e.length===0?"":(e=wc(e),e=cT(e),e=Tc(e),e=uT(e),e=lT(e),e=dT(e),e)}function yp(t){try{let e=fT(Ic(Sp(t)));return e.length>hp?e.slice(0,hp):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 bp(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 Ep,hp,_p,Me,vc=E(()=>{"use strict";Ep=_e(require("os"),1);M();hp=500,_p=8192,Me="[REDACTED]"});function gT(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!pT.has(r))continue;let n=t[r];if(typeof n=="string"){let s=n.length>wp?n.slice(0,wp):n;e[r]=Ic(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function ho(t){let e={};try{gT(t,e)}catch{}return e}var pT,wp,Rc=E(()=>{"use strict";vc();pT=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"]),wp=200});function _o(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function Eo(){return process.env.MEMINDEX_TELEMETRY_HOST||hT}function So(t){let e={};for(let r of _T)t[r]!==void 0&&(e[r]=t[r]);return e}function ET(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Ac.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 yo(){return{version:mT,os:process.platform,os_version:Ac.default.release(),is_wsl:ET(),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 Ac,mT,hT,_T,Mc=E(()=>{"use strict";Ac=_e(require("os"),1);M();mT="1.7.0",hT="https://us.i.posthog.com";_T=["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 Tp(t,e,r){try{if(!go(process.env,yn()))return;let n=ho({...yo(),...e??{}});if(r?.person?n.$set=So(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=_o(),o=new AbortController,i=setTimeout(()=>o.abort(),ST);try{await yT(s,t,n,o.signal)}finally{clearTimeout(i)}}catch{}}async function yT(t,e,r,n){await fetch(`${Eo()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:mo(),properties:r}),signal:n})}var ST,Ip=E(()=>{"use strict";bc();Rc();Mc();ST=2e3});var vp=E(()=>{"use strict";M()});var Rp=E(()=>{"use strict";M();vp()});function bn(t){return t.error?.name==="ETIMEDOUT"}function wn(t,e,r=Ap){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,bo.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})}})}).catch(o=>({status:null,stdout:"",error:o instanceof Error?o:new Error(String(o))}))}function Tn(t,e,r=Ap){let n=(0,bo.spawnSync)("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,bT),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 bo,Ap,bT,wo=E(()=>{"use strict";bo=require("child_process");M();Ap=5e3,bT=5e3});function Mp(t){let e=Ot.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)}),In}if(!r.isFile())return In;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)}),In}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return In;let o=Ot.default.resolve(Ot.default.dirname(e),s[1]),i=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Ot.default.basename(t),parentRepoPath:c,parentProjectName:Ot.default.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Ot.default.basename(t),parentRepoPath:c,parentProjectName:Ot.default.basename(c)}}return In}var To,Ot,In,Op=E(()=>{"use strict";To=require("fs"),Ot=_e(require("path"),1);M();In={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Pp(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 Pc(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,Oc.basename)(r);for(let s of e){let o=s.trim();if(o)try{let i=Pp(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 vn(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,Oc.basename)(r),s=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of s)try{let i=Pp(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 Oc,Rn=E(()=>{"use strict";Oc=require("path");qt();M()});function xp(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 wT(t){try{return(0,kp.realpathSync)(t)}catch{return t}}function kc(t,e){if(e.length===0)return null;let r=[...new Set([t,wT(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(s=>Pc(s,n.patterns)))return n.name;return null}var kp,Np=E(()=>{"use strict";kp=require("fs");Rn();M()});function Fp(t){let e=process.env[TT]?.trim();return e||(!t||t.trim()===""?null:t)}function Lp(t){return Up(t,Tn(t,["rev-parse","--show-toplevel"]))}async function RT(t){let e=Date.now(),r=Pr.get(t);if(r&&e-r.at<IT)return(await r.answer).root;Pr.size>=vT&&Pr.clear();let n=wn(t,["rev-parse","--show-toplevel"]).then(a=>({root:Up(t,a),kept:!bn(a)})),s={at:e,answer:n};Pr.set(t,s);let{root:o,kept:i}=await n;return!i&&Pr.get(t)===s&&Pr.delete(t),o}function Up(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 $p(t){try{return(0,xr.realpathSync)(t)}catch{return t}}function OT(t,e){let r=le.default.relative(e,t);return r===""||!r.startsWith("..")&&!le.default.isAbsolute(r)}function PT(){return[(0,Ro.homedir)(),(0,Ro.tmpdir)(),Be].flatMap(t=>{let e=le.default.resolve(t);return[e,$p(e)]})}function Bp(t){let e=PT(),r=le.default.resolve(t);if([le.default.resolve(Be),$p(le.default.resolve(Be))].some(s=>OT(r,s)))return null;for(let s=0;s<MT;s++){if(e.includes(r))return null;let o=le.default.dirname(r);if(o===r)return null;if(AT.some(i=>(0,xr.existsSync)(le.default.join(r,i))))return r;r=o}return null}function xc(t,e){let r=le.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}),Nc}return r}function Cp(){try{return(0,xr.statSync)(V).mtimeMs}catch{return-1}}function Wp(){let t=Cp();if(t===-1)return F.getAllDefaults();if(Io&&Io.mtimeMs===t)return Io.settings;let e=F.loadFromFile(V);return Io={mtimeMs:Cp(),settings:e},e}function Hp(){let t=process.env[kT]??Wp().MEMINDEX_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function jp(){let t=process.env[xT]??Wp().MEMINDEX_PROJECT_ENVIRONMENTS;return(!vo||vo.raw!==t)&&(vo={raw:t,environments:xp(t)}),vo.environments}function NT(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 Xp(t,e){return e.status===0&&e.stdout?NT(e.stdout):(f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},e.error),null)}function Kp(t){return Hp()?(kr.has(t)||kr.set(t,Xp(t,Tn(t,["remote","get-url","origin"]))),kr.get(t)??null):null}async function CT(t){if(!Hp())return null;if(!kr.has(t)){let e=await wn(t,["remote","get-url","origin"]);if(bn(e))return null;kr.set(t,Xp(t,e))}return kr.get(t)??null}function DT(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Nc;let r=Ee(t,e),n=kc(r,jp());if(n)return n;let s=Lp(r),o=s?Kp(s):null;if(o)return o;let i=s??Bp(r)??r;return xc(t,i)}function Gp(t,e){return e===t?t:`${t}/${e}`}function FT(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=le.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||le.default.isAbsolute(r)?null:r.split(le.default.sep).join("/")}function Ao(t,e=process.platform){if(!t||t.trim()==="")return zp(t,e);let r=Ee(t,e),n=Lp(r),s=n?Kp(n):null;return Vp(t,r,n,s)}async function An(t,e=process.platform){if(!t||t.trim()==="")return zp(t,e);let r=Ee(t,e),n=await RT(r),s=n?await CT(n):null;return Vp(t,r,n,s)}function zp(t,e){let r=DT(t,e);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function Vp(t,e,r,n){let s=LT(t,e,r),o=n?Dp(s,n,"git-remote"):s,i=kc(e,jp());return i?Dp(o,i,"environment"):o}function Dp(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function LT(t,e,r){let n=r?null:Bp(e),s=xc(t,r??n??e),o=r??e,i=Mp(o);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${FT(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&&le.default.resolve(n)!==le.default.resolve(e)){let a=xc(t,e);if(a!==s&&a!==Nc)return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,s],keySource:"path"}}return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}var le,xr,Ro,TT,Nc,IT,vT,Pr,AT,MT,kT,Io,xT,vo,kr,nr=E(()=>{"use strict";le=_e(require("path"),1),xr=require("fs"),Ro=require("os");qt();N();Ie();M();wo();Op();Np();TT="CLAUDE_PROJECT_DIR",Nc="unknown-project";IT=3e4,vT=500,Pr=new Map;AT=[".memindex-project",".memindex.json"],MT=64;kT="MEMINDEX_PROJECT_NAME_SOURCE",Io=null;xT="MEMINDEX_PROJECT_ENVIRONMENTS",vo=null;kr=new Map});function BT(t){try{return(0,ye.realpathSync)(t)}catch{return null}}function Cc(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function WT(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,Lc.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 Mn(t={}){let e=Object.keys(t).length===0;if(e&&Dc!==void 0)return Dc;let r=HT(t);return e&&r!==null&&(Dc=r),r}function Yp(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 HT(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,Fc.homedir)(),o=t.pathExists??ye.existsSync,i=t.lookupInPath??WT,a=t.realpath??BT,c=e==="win32"?[n.BUN,n.BUN_PATH,...Yp(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,...Yp(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 jT(){let t=B.dataDir();return(0,ye.mkdirSync)(t,{recursive:!0}),t}function XT(t,e,r,n=process.platform,s=(0,ye.existsSync)(qp)){let o=n!=="win32"&&s;return{command:o?qp:t,args:o?[t,e,"--daemon"]:[e,"--daemon"],options:{detached:!0,stdio:"ignore",cwd:jT(),env:r}}}function On(t,e,r,n=process.platform){let{command:s,args:o,options:i}=XT(t,e,r,n),a=uc(s,o,i);if(a.on("error",c=>{f.error("SYSTEM",$T,{runtimePath:t,execPath:s},c)}),a.pid!==void 0)return a.unref(),a.pid}var me,Fc,ye,Lc,zC,VC,$T,Dc,qp,Uc=E(()=>{"use strict";me=_e(require("path"),1),Fc=require("os"),ye=require("fs"),Lc=require("child_process");lc();M();En();Ec();Sn();Rp();nr();wo();N();it();zC=B.dataDir(),VC=B.workerPid(),$T="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.";qp="/usr/bin/setsid"});function $c(){return F.loadFromFile(V).MEMINDEX_WORKER_HOST}function Zp(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Qp(t,e,r="GET",n=sr){let s={method:r,signal:AbortSignal.timeout(Math.max(1,n))},o=await fetch(`http://${Zp($c())}:${t}${e}`,r==="GET"||r==="HEAD"?s:_n(s)),i="";try{i=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:i}}async function eg(t,e=sr){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${Zp($c())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(s)})}let n=await Mo(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function Mo(t,e=sr){return(await KT(t,e)).occupancy}function KT(t,e=sr){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,s=!1,o=!1,i;try{i=Jp.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"}):Nf(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,$c())}catch{try{i.close()}catch{}u({occupancy:"indeterminate"})}})}async function GT(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let i=s-Date.now();if((await Qp(t,e,"GET",Math.min(sr,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 tg(t,e=3e4){return GT(t,"/api/health",e,"Service not ready yet, will retry")}async function zT(t,e=sr){try{let r=await Qp(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 rg(t,e,r=sr){let n=e??"unknown",s=await zT(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}var Jp,sr,Oo=E(()=>{"use strict";Jp=_e(require("net"),1);M();Ie();N();qs();nc();it();sr=5e3});var ng=E(()=>{"use strict";M();Sn()});var sg=E(()=>{"use strict";Uc();Oo();ng()});function og(t){let e=VT.exec(t.trim());if(!e)return null;let r=e[4]===void 0?[]:e[4].split(".");return r.some(n=>n.length>1&&n.startsWith("0")&&Bc.test(n))?null:{core:[Number(e[1]),Number(e[2]),Number(e[3])],pre:r}}function YT(t,e){if(t.length===0||e.length===0)return e.length-t.length;for(let r=0;r<Math.min(t.length,e.length);r++){let n=Bc.test(t[r]),s=Bc.test(e[r]);if(n&&s){let o=Number(t[r])-Number(e[r]);if(o!==0)return o}else{if(n!==s)return n?-1:1;if(t[r]!==e[r])return t[r]<e[r]?-1:1}}return t.length-e.length}function qT(t,e){let r=og(t),n=og(e);if(r===null||n===null)return null;for(let s=0;s<3;s++)if(r.core[s]!==n.core[s])return r.core[s]-n.core[s];return YT(r.pre,n.pre)}function ig(t,e){let r=qT(t,e);return r===null?"unreadable":r>0?"upgrade":r<0?"plugin-older":"same"}var VT,Bc,ag=E(()=>{"use strict";VT=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,Bc=/^\d+$/});function lg(){return(0,Po.join)(x(),"spawn.lock")}function cg(t){try{let e=JSON.parse((0,ae.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function JT(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function ko(){let t=lg(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,ae.mkdirSync)((0,Po.dirname)(t),{recursive:!0}),(0,ae.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,ae.statSync)(t).mtimeMs}catch{continue}let a=cg(t),c=null;if(a===null)try{c=(0,ae.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-i<=ug&&JT(a)!==!1)return!1;let l;try{l=(0,ae.statSync)(t).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(cg(t)!==a)return!1}else try{if((0,ae.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,ae.unlinkSync)(t)}catch{return!1}}return!1}function Pn(){let t=lg();try{if(JSON.parse((0,ae.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,ae.unlinkSync)(t)}catch{}}var Po,ae,ug,mD,dg=E(()=>{"use strict";Po=require("path"),ae=require("fs");N();M();ug=9e4,mD=ug/3});function fg(t){return ZT.test(t.trim())}function QT(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 No(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function eI(t){try{let e=await xo("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:No(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 tI(t,e){try{let r=await xo("netstat",["-ano"],{timeout:No(15e3,e),windowsHide:!0,maxBuffer:16777216});return aI(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 rI(t,e){try{let r=await xo("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:No(1e4,e),maxBuffer:1048576});return nI(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 nI(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]}function sI(t,e){let r=e.toString(16).toUpperCase().padStart(4,"0"),n=[];for(let s of t.split(/\r?\n/).slice(1)){let o=s.trim().split(/\s+/);o.length<10||o[1].split(":").pop()?.toUpperCase()===r&&o[3]==="0A"&&o[9]!=="0"&&n.push(o[9])}return n}function oI(t,e={}){let r=e.deadlineAt??null,n=e.now??Date.now,s=()=>r!==null&&n()>=r;if(s())return null;let o=new Set,i=!1;for(let u of["/proc/net/tcp","/proc/net/tcp6"]){if(s())return null;try{for(let l of sI((0,je.readFileSync)(u,"utf8"),t))o.add(l);i=!0}catch{}}if(!i||s())return null;if(o.size===0)return[];let a;try{a=(0,je.readdirSync)("/proc")}catch{return null}let c=new Set;for(let u of a){if(s())return null;if(!/^\d+$/.test(u))continue;let l;try{l=(0,je.readdirSync)(`/proc/${u}/fd`)}catch{continue}for(let d of l){if(s())return null;try{let p=/^socket:\[(\d+)\]$/.exec((0,je.readlinkSync)(`/proc/${u}/fd/${d}`));if(p&&o.has(p[1])){c.add(Number.parseInt(u,10));break}}catch{}}}return s()?null:[...c]}async function iI(t,e){if(process.platform==="linux")try{return(0,je.readFileSync)(`/proc/${t}/cmdline`,"utf8").split("\0").filter(Boolean).join(" ")||null}catch{return null}try{let n=(await xo("ps",["-p",String(t),"-o","command="],{timeout:No(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function aI(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 uI(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let n=(l,d={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:l,...d}),{reclaimed:!1,reason:l,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 l=0;l<2;l++)if(l>0&&await e.sleep(_g),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=e.readHeartbeat();if(i?.pid===r.pid){let l=e.now(),d=Math.max(0,l-i.beatAtMs),p=Math.max(0,l-i.lastResponseAtMs);if(d<e.heartbeatStaleMs&&p<e.maxSilentProtectionMs)return n("owner-progressing",{heartbeatAgeMs:d,sinceLastResponseMs:p})}let a=await e.readIdentity(r.pid),c=r.startToken!==void 0&&a.startToken!==null&&a.startToken!==r.startToken;if(c||a.cmdline===null||!cI.test(a.cmdline))return n("owner-identity-mismatch",{tokenMismatch:c,hasCmdline:a.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:a.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(l){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},l instanceof Error?l:new Error(String(l))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let u=await e.listOwners(t);return u!==null&&u.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:u}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function lI(t,e,r,n){let s=Et(t),o=e?(await r(n))?.find(i=>i.pid===t)?.cmdline??null:await iI(t,n);return Re(t,s)?{startToken:s,cmdline:o}:{startToken:null,cmdline:null}}async function Eg(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(pg))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:i(),neededMs:pg}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((T,P)=>r()?tI(T,P):process.platform==="linux"?Promise.resolve(oI(T,{deadlineAt:s,now:n})):rI(T,P)),c=T=>a(T,i()),u=e.readTable??eI,l=()=>u(i()),d=e.killTree??((T,P)=>Ae(T,P)),p=e.dataDir??(()=>W),g=e.readIdentity??((T,P)=>lI(T,r(),u,P)),m=await uI(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??ot,probeHealth:e.probeHealth??(T=>tg(T,hg)),readIdentity:T=>g(T,i()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??Qd(),readHeartbeat:e.readHeartbeat??(()=>gI()),heartbeatStaleMs:e.heartbeatStaleMs??pI(),maxSilentProtectionMs:e.maxSilentProtectionMs??dI,now:n,sleep:e.sleep??(T=>new Promise(P=>setTimeout(P,T))),hasKillBudget:()=>!o(Wc)});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,v=new Set,I=T=>{for(let P of b.get(T)??[])v.has(P.pid)||(v.add(P.pid),I(P.pid),fg(P.name)&&w.set(P.pid,P))};for(let T of h)I(T);let y=p();if(y)for(let T of _)w.has(T.pid)||fg(T.name)&&QT(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 R=[];for(let T of w.values()){if(o(Wc))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:R}),{reclaimed:!1,reason:"out-of-budget",killedPids:R};try{await d(T.pid,{expectedStartToken:T.startToken,signalMode:"immediate"}),R.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:R}}}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:R}),{reclaimed:!0,killedPids:R}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:R,stillOwnedBy:A}),{reclaimed:!1,reason:"still-bound",killedPids:R})}function pI(t=process.env,e=V){let r=t.MEMINDEX_WORKER_HEARTBEAT_STALE_MS??F.loadFromFile(e,!1,{readOnly:!0}).MEMINDEX_WORKER_HEARTBEAT_STALE_MS,n=Number(r);return Number.isSafeInteger(n)&&n>=1e4&&n<=36e5?n:fI}function gI(t=B.workerHeartbeat()){try{let e=JSON.parse((0,je.readFileSync)(t,"utf8"));if(e&&Number.isSafeInteger(e.pid)&&Number.isFinite(e.beatAtMs)&&Number.isFinite(e.lastResponseAtMs))return{pid:e.pid,beatAtMs:e.beatAtMs,lastResponseAtMs:e.lastResponseAtMs}}catch{}return null}var gg,je,mg,xo,ZT,cI,hg,_g,Wc,pg,dI,fI,Sg=E(()=>{"use strict";gg=require("node:child_process"),je=require("node:fs"),mg=require("node:util");M();Ar();it();Sn();Oo();so();rt();N();Ie();xo=(0,mg.promisify)(gg.execFile),ZT=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;cI=/worker-service/i,hg=1500,_g=1e3,Wc=5500,pg=2*hg+_g+Wc;dI=6e5,fI=12e4});function yg(t){try{return(0,Nr.realpathSync)(t)}catch{return t}}function hI(t,e){let r=Pt.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!Pt.default.isAbsolute(r)}function wg(t){let e;try{let s=JSON.parse((0,Nr.readFileSync)(Pt.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=Pt.default.join(t,"node_modules"),n=e.filter(s=>!(0,Nr.existsSync)(Pt.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,bg.createRequire)(Pt.default.join(r,"noop.js")),o=yg(Pt.default.join(r,"zod"));for(let i of mI)try{let a=s.resolve(i,{paths:[r]});hI(yg(a),o)||n.push(i)}catch{n.push(i)}}return n}var Nr,bg,Pt,mI,Tg=E(()=>{"use strict";Nr=require("fs"),bg=require("module"),Pt=_e(require("path"),1),mI=["zod/v3","zod/v4","zod/v4-mini"]});function Rg(){return Co.default.join(x(),"worker-standby.json")}function Xc(){return Co.default.join(x(),"worker-standby-attempt.json")}function Kc(){return Co.default.join(x(),"worker-standby-failure.json")}function Gc(t){try{return JSON.parse((0,Do.readFileSync)(t,"utf-8"))}catch{return null}}function zc(t){try{(0,Do.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 Fo(){let t=Gc(Rg());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 Lo(t){if(t!==void 0){let e=Fo();if(e!==null&&e.pid!==t)return}zc(Rg())}function _I(){let t=Gc(Kc());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 Ag(t,e,r=new Date){try{$(Kc(),{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 Mg(){zc(Kc())}function Og(t,e=Date.now()){if(t===null)return null;let r=_I();if(r===null||r.buildKey!==t)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||e-n>=jc?null:r}function Pg(){let t=Gc(Xc());return!t||typeof t.buildKey!="string"||typeof t.launchedAtMs!="number"||!Number.isFinite(t.launchedAtMs)?null:{buildKey:t.buildKey,launchedAtMs:t.launchedAtMs}}function kg(t){try{$(Xc(),t)}catch(e){f.debug("SYSTEM","Could not save the worker update attempt",{error:e instanceof Error?e.message:String(e)})}}function xg(){zc(Xc())}var Co,Do,Ig,Hc,vg,jc,Ng=E(()=>{"use strict";Co=_e(require("path"),1),Do=require("fs");N();oe();M();Ig="MEMINDEX_WORKER_STANDBY",Hc=12e4,vg=2e4,jc=10*6e4});function Qc(t,e,r){let n=process.env[t];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=r.min&&s<=r.max)return s;f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}function Yg(t=process.env){let e=t.MEMINDEX_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function bI(t){return Yg()?{...t,verbose:!0}:t}function wI(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 TI(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=wI(r),o=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},o),mt(`[memindex] fetch verbose: ${n} ${t} ${o}
22
+ `)}async function Dn(t,e={}){let r=bI(e);try{return await fetch(t,r)}catch(n){throw Yg()&&TI(t,e,n),n}}async function Cr(t,e={},r){try{return await Dn(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 II(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 qg(t,e,r){let n=II(r,e.signal),s;try{s=await Dn(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 vI(t,e,r){let n=await qg(t,e,r),s=new TextDecoder,o="";for await(let i of n.chunks)o+=s.decode(i,{stream:!0});return o+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:o}}function Cg(){return U.default.join(F.get("MEMINDEX_DATA_DIR"),"settings.json")}function tu(t={}){return t.readOnly?F.loadFromFile(Cg(),!0,t):(Uo!==null||(Uo=F.loadFromFile(Cg())),Uo)}function Dg(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Jg(t,e,r){let n=process.env[t];if(n!==void 0){let i=Dg(n,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=tu()[t],o=Dg(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 te(t={}){if(!t.readOnly&&Vc!==null)return Vc;let e=parseInt(tu(t).MEMINDEX_WORKER_PORT,10),r=e===ja()&&pn()?Ka(x()):e;return t.readOnly||(Vc=r),r}function Xo(t={}){if(!t.readOnly&&Yc!==null)return Yc;let e=tu(t).MEMINDEX_WORKER_HOST;return t.readOnly||(Yc=e),e}function RI(){return $o!==null||($o=Jg("MEMINDEX_API_TIMEOUT_MS",Rt(ie.API_REQUEST),SI)),$o}function Zg(){return Bo!==null||(Bo=Math.min(Jg("MEMINDEX_SESSION_INIT_TIMEOUT_MS",ln(),yI),ef())),Bo}function Qg(t){return t===null?null:Math.max(0,t-Date.now())}function Ho(t){let e=Qg(t);return e!==null&&e<eu}function Oe(t,e){let r=Qg(e);return r===null?t:Math.max(1,Math.min(t,r))}function Cn(t){return`http://${ic(Xo())}:${te()}${t}`}function AI(t){let e=t.split("?")[0].toLowerCase().replace(/\/+$/,"");return e==="/api/health"||e==="/api/readiness"||e==="/api/ready"}async function OI(t){if(!await Qs(Cn(""),{timeoutMs:t,fetchImpl:Dn}))throw Fg||(Fg=!0,f.warn("SECURITY","The listener on the worker port did not prove it is this install's worker; nothing was sent to it",{port:te(),host:Xo()})),new Rr(MI)}async function be(t,e={}){let r=e.method??"GET",n=Cn(t),s={method:r};e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body);let o=AI(t),i=Date.now(),a=e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0?e.timeoutMs:e.timeoutMs??RI(),c=()=>Date.now()-i,u=l=>l===void 0||l<=0?l:Math.max(1,l-c());try{o||await OI(a!==void 0&&a>0?Math.min(Pe,a):Pe);let l=o?s:_n(s);if(e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0){let p=await vI(n,l,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:u(e.timeoutMs)});return new Response(p.text.length>0?p.text:null,{status:p.status,statusText:p.statusText,headers:p.headers})}let d=u(a)??0;return d>0?await Cr(n,l,d):await Dn(n,l)}catch(l){throw l instanceof Rr||$f(),l}}async function PI(t){return(await be("/api/health",{timeoutMs:t})).ok}async function Lg(t=Pe){return(await be("/api/readiness",{timeoutMs:t})).ok}function em(t){let e=(0,k.existsSync)(U.default.join(t,"plugin","scripts"))?U.default.join(t,"plugin"):t;return U.default.join(e,"scripts","worker-service.cjs")}function kI(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 xI(t=U.default.join(U.default.dirname(U.default.dirname(wr)),"cache","memindex","memindex")){try{return(0,k.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>U.default.join(t,e)).filter(e=>{try{if(!(0,k.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,k.existsSync)(U.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:em(e),version:U.default.basename(e)}))}catch{return[]}}function Ug(t){try{let e=JSON.parse((0,k.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function NI(){return{cacheRoot:U.default.join(U.default.dirname(U.default.dirname(wr)),"cache","memindex","memindex"),marketplaceRoot:wr,cwd:process.cwd()}}function ru(t=NI()){let e=process.env.MEMINDEX_WORKER_SCRIPT_PATH?.trim();if(e){if((0,k.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing MEMINDEX_WORKER_SCRIPT_PATH override",{override:e})}let r=$g([...xI(t.cacheRoot),{scriptPath:em(U.default.join(t.marketplaceRoot,"plugin")),version:Ug(U.default.join(t.marketplaceRoot,"package.json"))}]);return r||!Yd()?r:$g([{scriptPath:U.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:Ug(U.default.join(t.cwd,"package.json"))}])}function CI(t){return U.default.dirname(U.default.dirname(t))}function DI(t){return wg(CI(t.scriptPath)).length===0}function $g(t,e=DI){let r=t.filter(n=>(0,k.existsSync)(n.scriptPath));return r.length===0?null:(r.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:kI(n.version,s.version)),r.find(e)??r[0])}function FI(){return ru()?.scriptPath??null}async function LI(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(Ho(e))return!1;if(await um(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,Oe(r,e))),r*=2)}return!1}function Bg(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function Wg(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function UI(t){let e;try{e=await qg(Cn("/api/ready"),{method:"GET"},{idleTimeoutMs:EI,absoluteCapMs:Math.max(1,t)})}catch(o){return Bg(o)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:Wg(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 jo(),await r(),{outcome:"unsupported"};let s=null;try{for await(let o of Hf(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 jo(),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 Wg(o)?(jo(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):Bg(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 $I(t){if(t<=0)try{return await Lg()?{outcome:"ready"}:{outcome:"still_booting"}}catch(r){return f.debug("SYSTEM","Worker readiness check threw",{},r instanceof Error?r:new Error(String(r))),{outcome:"still_booting"}}let e=Date.now();do{let r=t-(Date.now()-e);try{if(await Lg(Math.max(1,Math.min(Pe,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 kt(t=ir){let e=t>0?t:Pe,r=await UI(e);return r.outcome==="ready"&&GI(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),$I(t))}async function BI(t=Pe){try{let r=await(await be("/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 WI(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await Mo(te(),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 tm(t,e){if(!t)return null;try{let r=(0,k.statSync)(t.scriptPath);return JSON.stringify([t.scriptPath,e,r.size,r.mtimeMs,r.ctimeMs])}catch{return null}}function rm(){return U.default.join(x(),"worker-version-recycle.json")}function HI(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,k.readFileSync)(rm(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function Hg(t,e=null,r=Pe){let n=await BI(r);if(n!==null&&n!==t){if(e!==null)try{$(rm(),{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 nu(){return U.default.join(x(),"worker-unresponsive.json")}function jI(){try{let t=JSON.parse((0,k.readFileSync)(nu(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function jo(){let t=nu();if((0,k.existsSync)(t))try{(0,k.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function XI(t=Date.now()){let e=ot()?.pid??null;if(e===null)return!1;let r=jI();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=nm;try{$(nu(),{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 su(){return U.default.join(x(),"worker-never-ready-recycle.json")}function KI(){try{let t=JSON.parse((0,k.readFileSync)(su(),"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 sm(t){try{$(su(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function GI(){let t=su();if((0,k.existsSync)(t))try{(0,k.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function om(t){return tm(t,t?.version??"unknown")??"unresolved-worker-bundle"}function im(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function am(t,e){if(t.outcome==="unresponsive"&&!XI())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:nm}),!1;let r=im(t),n=KI();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:U.default.join(x(),"logs")}),sm({...n,refusalLogged:!0})),!1):!0}function cm(t,e){sm({buildKey:e,failureMessage:im(t)}),jo()}async function um(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await PI(Math.min(Pe,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function ou(t,e){let r=ot();if(r===null||r.port!==te())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:te(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await Ae(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 WI(Oe(5e3,t))?!0:(e("stale port release")||(ar=te(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:te(),fix:Ko})),!1)}function Jc(t,e){return`http://127.0.0.1:${t}${e}`}async function lm(t,e){if(e<=0)return{answered:!1,version:null};try{let n=await(await Cr(Jc(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 dm(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)})}Lo(t.pid)}async function zI(t,e,r,n){let s=await VI(t,e,r,n);return s.kind!=="out-of-budget"&&xg(),s}async function VI(t,e,r,n){let s=Fo(),o=s===null?null:await lm(s,Oe(Pe,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(kn/1e3)} seconds; the worker log has the reason`};if(s!==null&&o!==null)if(o.answered)dm(s);else{let d=Date.parse(s.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<Hc&&q(s.pid)){let g=Math.min(d+Hc,Math.max(d+kn,Date.now()+2e3)),m=await qc(e,g,n,i);return m.kind==="failed"&&Lo(s.pid),m}Lo(s.pid)}let a=r===null?null:Pg();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=kn?i:qc(e,a.launchedAtMs+kn,n,i);let c=Mn();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=On(c,t,He({...process.env,MEMINDEX_WORKER_PORT:String(te()),[Ig]:"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&&kg({buildKey:r,launchedAtMs:l}),qc(e,l+kn,n,i)}async function qc(t,e,r,n){let s=Math.min(e,r??Number.POSITIVE_INFINITY);for(;Date.now()<s;){let o=Fo();if(o!==null){let a=await lm(o,Math.min(1e3,s-Date.now()));if(a.answered)return a.version===t?{kind:"ready",record:o}:(dm(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 YI(t,e){try{if(!await Qs(Jc(t.port,""),{timeoutMs:e,fetchImpl:Dn}))return"the standby worker did not prove it holds this install's secret";let r=await Cr(Jc(t.port,"/api/admin/promote"),_n({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 qI(t){let{scriptPath:e,pluginVersion:r,workerVersion:n,buildKey:s,deadlineAt:o,outOfBudget:i}=t,a=n??"unknown",c=Og(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=ot();if(u===null||u.port!==te())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:te(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),"failed";if(!ko())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 zI(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&&Ag(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(jc/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 ou(o,i))return"failed";l=!0;let p=await YI(d.record,Oe(1e4,o));return p===null?(Mg(),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||Pn()}}async function Fn(t){let e=t===void 0?null:Date.now()+t,r=S=>Ho(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:Oe(Pe,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),o=ru(),i=null,a=null,c=!1,u=!1,l=!1,d=null,p=null,g=to(z());if(r("health probe"))return!1;if(await um(s)){if(r("version probe"))return!1;let{matches:S,pluginVersion:b,workerVersion:w}=await rg(te(),o?.version??null,n());if(b!=="unknown"&&(i=b),S){if(r("readiness wait"))return!1;let v=await kt(Oe(ir,e));if(v.outcome==="ready")return i!==null&&!Ho(e)&&await Hg(i,null,n()),!0;if(v.outcome==="still_booting"||v.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:v.outcome,detail:v.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:v.outcome,detail:v.detail}),!1;if(p=om(o),!am(v,p))return!1;d=v,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:v.outcome,detail:v.detail,version:w})}else{let v=w===null?"unreadable":ig(b,w);if(v!=="upgrade")return jg||(jg=!0,f.info("SYSTEM",v==="plugin-older"?"This plugin is older than the running worker, so the running worker stays; update this session (npx memindex update) to use the newer one":"Could not tell which of the plugin and the running worker is newer, so the running worker stays",{pluginVersion:b,workerVersion:w})),r("readiness wait")?!1:(await kt(Oe(ir,e))).outcome==="ready";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 kt(Oe(ir,e))).outcome==="ready";if(a=tm(o,b),HI(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 kt(Oe(ir,e))).outcome==="ready";f.info("SYSTEM","Worker version changed \u2014 starting the new worker before stopping the old one",{pluginVersion:b,workerVersion:w});let I=await qI({scriptPath:o?.scriptPath??null,pluginVersion:b,workerVersion:w,buildKey:a,deadlineAt:e,outOfBudget:r});if(I==="failed")return!1;if(I==="kept-old")return r("readiness wait")?!1:(await kt(Oe(ir,e))).outcome==="ready";u=!0,l=I==="promoted"}if(!u&&!await ou(e,r))return!1;d!==null&&p!==null&&cm(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&&Pn(),!1;let h=u||ko();try{if(h&&!l){if(!c&&!await JI(s,e,m))return!1;let b=Mn();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(On(b,m,He({...process.env,MEMINDEX_WORKER_PORT:String(te())}),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 LI({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)"),ot()===null&&await eg(te(),e===null?void 0:Oe(5e3,e))&&(ar=te(),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:ar,fix:Ko}))),!1}finally{h&&Pn()}if(r("readiness wait"))return!1;let _=await kt(Oe(ir,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&&!Ho(e)&&await Hg(i,a,n()),!0)}async function JI(t,e,r){let n=te(),s=t-Date.now();if(s<=0)return!1;let o=await Mo(n,s);if(o==="free")return!0;if(o==="unbindable")return Zc=n,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:n,host:Xo(),fix:Ja}),!1;if(o==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:n}),!1;let i=await Eg(n,{deadlineAt:e});return i.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:n,killedPids:i.killedPids}),!0):(i.reason==="out-of-budget"&&e!==null&&tv(n,r),ot()===null&&(ar=n),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:n,reclaimReason:i.reason,...ar===n?{fix:Ko}:{}}),!1)}function ev(t){let e;try{e=Date.now()-(0,k.statSync)(t).mtimeMs}catch{return!1}if(e<ZI)return!0;if(e>=QI)return!1;try{let{daemonPid:r}=JSON.parse((0,k.readFileSync)(t,"utf8"));return!Number.isInteger(r)||r<=0||q(r)}catch{return!0}}function tv(t,e){let r=U.default.join(x(),"reclaim-handoff.json");if(ev(r))return;let n=Mn();if(!n||!e)return;let s=i=>{$(r,{hookPid:process.pid,daemonPid:i,port:t})},o=()=>{try{(0,k.unlinkSync)(r)}catch{}};try{s(null)}catch(i){f.warn("SYSTEM","Could not record the reclaim handoff; skipping detached reclaim",{port:t},i instanceof Error?i:new Error(String(i)));return}try{let i=On(n,e,He({...process.env,MEMINDEX_WORKER_PORT:String(t)}),process.platform);if(i===void 0){o();return}if(i>0)try{s(i)}catch{}f.info("SYSTEM","Handed the port reclaim to a detached worker daemon",{port:t,daemonPid:i})}catch(i){o(),f.warn("SYSTEM","Could not launch the detached reclaim daemon",{port:t},i instanceof Error?i:new Error(String(i)))}}async function rv(t){if(or!==void 0)return or;try{let e=Za(),n=await(await Cr(rc(Cn(""),e),{method:"GET",redirect:"error"},t)).json();Qa(n.proof,e)&&tc(Cn("")),or=hf(n.dataDir,x())==="foreign"?String(n.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)}),or=null}return or!==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:or,dataDir:x(),port:te()}),or}async function nv(t){return Wo!==null||(Wo=await Fn(t)),Wo}async function sv(t){let e=Date.now()+t,r=()=>e-Date.now(),n=u=>r()>=eu?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:u,budgetMs:t}),!0),s=await kt(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(!!to(z()))return Xg(e);let i=Mn(),a=FI();if(!i||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let u=om(ru());if(!am(s,u)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await ou(e,n)))return!1;cm(s,u)}let c=ko();try{return c&&On(i,a,He({...process.env,MEMINDEX_WORKER_PORT:String(te())}),process.platform)===void 0?!1:await Xg(e)}catch(u){return f.debug("SYSTEM","Bounded worker startup failed",{error:u instanceof Error?u.message:String(u)}),!1}finally{c&&Pn()}}async function Xg(t){for(;t-Date.now()>0;){let e=await kt(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 Go(){return U.default.join(W,"state")}function mm(){return U.default.join(Go(),"hook-failures.json")}function hm(){return U.default.join(Go(),"hook-failures.lock")}async function iu(t=pm){let e=Go(),r=hm(),n=(0,Vg.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),o=Date.now()+t;for(;Date.now()<=o;)try{return(0,k.mkdirSync)(e,{recursive:!0}),(0,k.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,k.statSync)(r).mtimeMs}catch{continue}if(Date.now()-u>gm){let l;try{l=(0,k.statSync)(r).mtimeMs}catch{continue}if(l===u)try{(0,k.unlinkSync)(r);continue}catch{}}await new Promise(l=>setTimeout(l,iv))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function au(t){let e=hm();try{if(JSON.parse((0,k.readFileSync)(e,"utf-8")).token!==t)return;(0,k.unlinkSync)(e)}catch{}}function cv(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(-fm):void 0}}function Nn(){try{return cv((0,k.readFileSync)(mm(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function cu(t){let e=Go(),r=mm(),n=`${r}.tmp`;try{return(0,k.existsSync)(e)||(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(n,JSON.stringify(t),"utf-8"),(0,k.renameSync)(n,r),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function uv(){try{let e=z().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return ov}function _m(t){let e=Zc!==null?`The worker cannot bind port ${Zc} on ${Xo()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Ja}.`:ar!==null?`Port ${ar} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${Ko}.`:"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 xn(){if(lv){if(Gg)return Nn().consecutiveFailures;Gg=!0}let t=await iu();if(t===null)return Nn().consecutiveFailures;let e,r=!1;try{let n=Nn();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=uv();r=e.consecutiveFailures>=s&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let o=cu(e);r=r&&o}finally{au(t)}return r&&(await Tp("hook_failed",{...Kg!==null?{hook_type:Kg}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),mt(`${_m(e.consecutiveFailures)}
23
+ `)),e.consecutiveFailures}async function Em(t){if(!t)return null;let e=await iu();if(e===null)return null;try{let r=Nn(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:cu({...r,notifiedSessionIds:[...n,t].slice(-fm)})?_m(r.consecutiveFailures):null}finally{au(e)}}async function zg(){let t=await iu(av);if(t!==null)try{let e=Nn();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;cu({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{au(t)}}function Sm(t){return typeof t=="object"&&t!==null&&t[St]===!0}async function ym(t,e,r,n={}){let s=Date.now(),o=n.workerStartupTimeoutMs!==void 0;if(!(o?await sv(n.workerStartupTimeoutMs):await nv(n.timeoutMs)))return to(z())?{continue:!0,reason:"worker_autostart_disabled",[St]:!0}:(o||await xn(),{continue:!0,reason:"worker_unreachable",[St]:!0});let a=n.timeoutMs===void 0?Pe:Math.max(1,Math.min(Pe,n.timeoutMs-(Date.now()-s)));if(await rv(a)!==null)return await xn(),{continue:!0,reason:"worker_foreign_data_dir",[St]:!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<eu)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),o||await xn(),{continue:!0,reason:"worker_budget_exhausted",[St]:!0};c.timeoutMs=d}let u;try{u=await be(t,c)}catch(d){if(d instanceof Rr)return await xn(),{continue:!0,reason:"worker_unverified",[St]:!0};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",[St]:!0}}if(!u.ok){let d=await u.text().catch(()=>"");if(await zg(),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}`,[St]:!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 xn(),{continue:!0,reason:"worker_body_read_failed",[St]:!0}}if(await zg(),l.length!==0)try{return JSON.parse(l)}catch{return l}}var U,Vg,k,Pe,ir,kn,EI,SI,yI,eu,Vc,Yc,Uo,$o,Bo,Fg,MI,nm,jg,Ko,ar,Zc,ZI,QI,Wo,or,ov,fm,pm,iv,gm,av,Kg,lv,Gg,St,xt=E(()=>{"use strict";nc();U=_e(require("path"),1),Vg=require("crypto"),k=require("fs");M();rt();jf();Ie();N();st();Xf();Kf();ac();Ga();Sn();it();Ws();Ip();sg();ag();Oo();qs();Uc();dg();Sg();En();Ar();oe();Tg();Ng();ac();Pe=Qc("MEMINDEX_HEALTH_TIMEOUT_MS",Rt(ie.HEALTH_CHECK),{min:500,max:3e5}),ir=Qc("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",Rt(ie.HOOK_READINESS_WAIT),{min:0,max:3e5}),kn=Qc("MEMINDEX_WORKER_STANDBY_WAIT_MS",vg,{min:500,max:3e5}),EI=5e3,SI={min:500,max:3e5},yI={min:500,max:ie.SESSION_INIT_REQUEST_MAX},eu=100;Vc=null,Yc=null,Uo=null,$o=null,Bo=null;Fg=!1,MI="The program answering on the MemIndex worker port did not prove it holds this install's secret, so MemIndex sent it nothing. Notes wait in the hook spool until the real worker answers. If this keeps happening, run npx memindex doctor.";nm=3e4;jg=!1;Ko="Set MEMINDEX_WORKER_PORT to a different port in memindex settings, or reboot to release the stuck port",ar=null,Zc=null;ZI=3e4,QI=12e4;Wo=null;ov=3,fm=20,pm=1e3,iv=10,gm=5e3,av=gm+pm;Kg=null;lv=!1,Gg=!1;St=Symbol.for("memindex/worker-fallback")});function uu(t,e){let r=(0,at.normalize)(t),n=(0,at.normalize)(e);if(r===n)return!0;let s=(0,at.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,at.isAbsolute)(s)}function ct(t){if(process.env.MEMINDEX_INTERNAL==="1")return!1;if(!t)return!0;if(uu(t,js)||uu(t,hv)||uu(t,_v))return!1;let e=z();return!vn(t,e.MEMINDEX_EXCLUDED_PROJECTS)}var at,dv,fv,pv,gv,mv,hv,_v,Dr=E(()=>{"use strict";at=require("path");Rn();st();N();dv="plugins",fv="cache",pv="memindex",gv="memindex",mv="plugin",hv=(0,at.join)(Be,dv,fv,pv,gv),_v=(0,at.join)(wr,mv)});function Ev(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Y(t){if(!t)return bm;let e=Ev(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:bm}var bm,ut=E(()=>{"use strict";bm="claude"});var wm=E(()=>{"use strict"});function Mm(t){let e=Object.fromEntries(lu.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}Im.lastIndex=a;let l=Im.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}Tm.lastIndex=a;let d=Tm.exec(t);if(d&&Sv.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 zo(t){let e="",r=0;for(;;){let n=t.indexOf(vm,r);if(n===-1)break;let s=t.indexOf(Rm,n+vm.length);if(s===-1)break;e+=t.slice(r,n),r=s+Rm.length}return r===0?t:e+t.slice(r)}function yv(t){let{text:e,counts:r,total:n}=Mm(t);return n>Am&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:Am,contentLength:t.length}),{stripped:Gs(e.trim(),La()).redacted,counts:r}}function we(t){return yv(t).stripped}function bv(t){return t.includes("<")&&lu.some(e=>t.includes(`<${e}`))}function Ln(t){let e=r=>typeof r=="string"?bv(r)&&Mm(r).total>0?we(r):r:Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,s])=>[n,e(s)])):r;return e(t)}function Vo(t){return!t||t.length>Iv?!1:Tv.test(t)}function Om(t){let e=t.trimStart();return vv.some(r=>r.test(e))}var lu,Sv,Tm,Im,vm,Rm,Am,wv,Tv,Iv,vv,lt=E(()=>{"use strict";M();Ua();lu=["private","memindex-context","agent-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Sv=new Set(lu),Tm=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Im=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;vm="<system-reminder>",Rm="</system-reminder>";Am=100;wv=["task-notification"],Tv=new RegExp(`^\\s*<(${wv.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Iv=256*1024;vv=[/^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 Av(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 Ke(t){return t instanceof Xe}function Mv(t){return t.replace(/\/+$/,"")}function Yo(t){return typeof t=="string"?Y(t):null}function Ov(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var Rv,Xe,qo,cr=E(()=>{"use strict";xt();rt();ut();lt();Rv=Rt(ie.API_REQUEST),Xe=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)}},qo=class{baseUrl;apiKey;timeoutMs;branchRejected=!1;constructor(e){this.baseUrl=Mv(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Rv}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 Xe("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 Xe("invalid_response","id is required for updateObservation");await this.request("PATCH",`/v1/memories/${encodeURIComponent(e)}`,r)}async deleteObservation(e){if(!e)throw new Xe("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=Yo(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 Xe("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:Yo(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:Yo(e.platformSource)}:{},...e.metadata!==void 0?{metadata:Ln(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:Yo(e.platformSource)}:{},...e.payload!==void 0?{payload:Ln(e.payload)}:{},...e.branch?{branch:e.branch}:{}}}async request(e,r,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new Xe("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 Xe(m?"timeout":"transport",`Server ${e} ${r} failed: ${g}`,{cause:p})},u,l=s.timeoutMs??this.timeoutMs;try{u=await Cr(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)&&Av(p))return this.branchRejected=!0,this.request(e,r,n,s);throw new Xe("http_error",`Server ${e} ${r} returned ${u.status}: ${Ov(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 Xe("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:g})}}}});function Pv(){let e=(z().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function kv(){let t=z(),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 xv(){let{serverBaseUrl:t,apiKey:e,projectId:r}=kv();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 qo(n),projectId:r,serverBaseUrl:t}}function Ge(){if(Pv()!=="server")return{runtime:"worker"};let t=xv();return t||{runtime:"worker"}}function ze(t,e){f.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var Fr=E(()=>{"use strict";st();M();cr()});function Lv(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 Ve(t){let e=(0,gu.createHash)("sha256").update(Lv(t.serverBaseUrl)).update("\0").update(t.projectId).digest("hex").slice(0,16);return(0,Nt.join)(x(),"state","server-outbox",e)}function mu(t){return(0,Nt.join)(t,"outage.json")}function yt(t){return Ke(t)&&t.isFallbackEligible()&&t.kind!=="missing_api_key"}function Uv(){return du=Math.max(Date.now(),du+1),du}function $v(t,e){let r=(0,gu.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16);return`${String(t).padStart(15,"0")}-${e.op}-${r}.json`}function Ct(t,e){(0,K.mkdirSync)(e,{recursive:!0});let r=Ln(t),n=Uv(),s=(0,Nt.join)(e,$v(n,r));return $(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 xm(t){return(0,K.existsSync)(t)?(0,K.readdirSync)(t).filter(e=>e.endsWith(".json")&&e!=="outage.json").sort():[]}function pu(t){try{return xm(t).length}catch{return 0}}function Bv(t){for(let e of(0,K.readdirSync)(t)){if(!e.endsWith(`.json${fu}`))continue;let r=(0,Nt.join)(t,e);try{if(Date.now()-(0,K.statSync)(r).mtimeMs<Nv)continue;(0,K.renameSync)(r,r.slice(0,-fu.length))}catch{}}}async function hu(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 Wv(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 hu(t,e.request,s,n)}function km(t,e,r){try{(0,K.mkdirSync)((0,Nt.join)(t,Pm),{recursive:!0}),(0,K.renameSync)(e,(0,Nt.join)(t,Pm,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 Lr(t,e,r={}){let n=r.maxEntries??Dv,s=Date.now()+(r.budgetMs??Fv),o={delivered:0,remaining:0,rejected:0};try{if(!(0,K.existsSync)(e))return o;Bv(e);let i=xm(e),a=0;for(let c of i){if(a>=n||Date.now()>=s)break;let u=(0,Nt.join)(e,c),l=`${u}${fu}`;try{(0,K.renameSync)(u,l)}catch{continue}try{let p=new Date;(0,K.utimesSync)(l,p,p)}catch{}a++;let d;try{if(d=JSON.parse((0,K.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))),km(e,l,c),o.rejected++;continue}try{let p=m=>{try{$(l,{...d,entry:{op:"summarize",request:m}})}catch{}},g=a===1?Math.max(s,Date.now()+ie.API_REQUEST):s;await Wv(t,d.entry,g,p),(0,K.unlinkSync)(l),o.delivered++}catch(p){if(yt(p)){(0,K.renameSync)(l,u);break}f.error("HOOK","Hosted server refused a held capture; moved aside",{name:c,op:d.entry.op,status:Ke(p)?p.status:null},p instanceof Error?p:new Error(String(p))),km(e,l,c),o.rejected++}}o.remaining=pu(e),o.delivered>0&&f.info("HOOK","Sent held captures to the hosted server",{...o}),o.remaining===0&&jv(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=pu(e)}return o}function Hv(t){try{let e=JSON.parse((0,K.readFileSync)(mu(t),"utf-8"));return{notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds:[]}}catch{return{notifiedSessionIds:[]}}}function jv(t){try{(0,K.unlinkSync)(mu(t))}catch{}}function Xv(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 Nm(t,e){if(!t)return null;let r=pu(e);if(r===0)return null;let n=Hv(e);if(n.notifiedSessionIds.includes(t))return null;try{$(mu(e),{notifiedSessionIds:[...n.notifiedSessionIds,t].slice(-Cv)})}catch{}return Xv(r)}var gu,K,Nt,fu,Pm,Nv,Cv,Dv,Fv,du,Un=E(()=>{"use strict";gu=require("crypto"),K=require("fs"),Nt=require("path");oe();N();rt();M();lt();cr();fu=".sending",Pm="rejected",Nv=120*1e3,Cv=50,Dv=20,Fv=1500;du=0});function Zo(t){return eR.run(t,!0)}function tR(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 rR(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 nR(t){let e=t.replace(Yv," ").toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu)??[],r=[...new Set(e)].slice(0,Vv);return r.length>0?r.join(" or "):null}async function sR(t,e,r,n,s,o,i){if(e.length<20||e==="[media prompt]")return"";let a=nR(e);if(!a)return"";let c=_u(o,i);if(c<Jo)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,aR(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,qv):""}catch(u){return f.warn("HOOK","session-init: server semantic context unavailable",{error:u instanceof Error?u.message:String(u)}),""}}function oR(t){let e=String(t.MEMINDEX_SEMANTIC_INJECT).toLowerCase();return e==="auto"?String(t.MEMINDEX_MODE).toLowerCase()==="personal":e==="true"}function iR(t){let e=String(t.MEMINDEX_READ_ONLY??"").toLowerCase();return e==="1"||e==="true"}async function Cm(t,e,r,n,s,o,i){if(!e||e.length<20||e==="[media prompt]")return"";let a=_u(o,i);if(a<Jo)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},Dm(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 aR(t){let e=typeof t=="number"?t:Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?5:e}function _u(t,e){return Math.max(0,e-(Date.now()-t))}function Dm(t,e){return t==="codex"?{workerStartupTimeoutMs:ie.POST_SPAWN_WAIT,timeoutMs:Math.min(Jv,e)}:{timeoutMs:e}}var Gv,de,zv,Vv,Yv,qv,Jo,Jv,Ur,Zv,Qv,eR,Eu=E(()=>{"use strict";xt();nr();M();rt();Dr();st();ut();wm();lt();Fr();cr();Un();Gv={executeWithWorkerFallback:ym,getSessionInitRequestTimeoutMs:Zg,isWorkerFallback:Sm,consumeWorkerOutageNotice:Em,loadFromFileOnce:z,resolveRuntimeContext:Ge,logServerFallback:ze,holdForServer:Ct,consumeServerOutageNotice:Nm,shouldTrackProject:ct,readHookEnvironment:()=>process.env},de=Gv,zv=2,Vv=12,Yv=/<private\b[^>]*>[\s\S]*?<\/private\s*>/gi,qv=1e4,Jo=500,Jv=2e3,Ur=class extends Error{constructor(r){super(`session-init did not record the prompt (${r})`);this.reason=r;this.name="SessionPromptNotRecordedError"}reason};Zv=t=>t?t.replace(/\\/g,"/").includes("/.qwen/"):!1,Qv=(t,e=process.env)=>t?e.QWEN_PROJECT_DIR?!0:Zv(t):!1,eR={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&&Vo(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&Y(t.platform)==="codex"&&Om(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()&&Qv(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=Ao(o),u=c.primary,l=Y(t.platform),d=de.loadFromFileOnce(),p=oR(d),g=de.resolveRuntimeContext(),m=Date.now(),h=de.getSessionInitRequestTimeoutMs();if(g.runtime==="server"){let I=tR(g,t,r,l,u,a);try{await rR(g,I,Math.max(Jo,Math.floor(h/zv)));let y=p?await sR(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(yt(y)){de.logServerFallback(y.kind,{status:y.status,message:y.message,route:"/v1/sessions/start",held:!0});let R=Ve(g);de.holdForServer({op:"session_start",request:I},R);let A=de.consumeServerOutageNotice(r,R);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...A?{systemMessage:A,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:A}}:{}}}if(Ke(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(iR(de.readHookEnvironment())){let I=p?await Cm(d,a,u,c.allProjects,l,m,h):"";return I?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:I}}:{continue:!0,suppressOutput:!0}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:u});let _=_u(m,h);if(_<Jo){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:_}),e)throw new Ur("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},Dm(l,_));if(de.isWorkerFallback(S)){if(e)throw new Ur("reason"in S?S.reason:"worker_fallback");let I=await de.consumeWorkerOutageNotice(r);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...I?{systemMessage:I}:{}}}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 v=p?await Cm(d,a,u,c.allProjects,l,m,h):"";return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | project=${u}`,{sessionId:b}),v?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:v}}:{continue:!0,suppressOutput:!0}}}});var Fm=E(()=>{"use strict";qt();N()});function ri(){return(0,Ye.join)(x(),"state","hook-spool")}function ei(t){if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(Array.isArray(t))return`[${t.map(ei).join(",")}]`;let e=t;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${ei(e[n])}`).join(",")}}`}function pR(t,e){if(t==="summarize"&&e.turnId){let n=e;return(0,Qo.createHash)("sha256").update(ei({contentSessionId:n.contentSessionId,platformSource:Y(n.platformSource),turnId:n.turnId,lastAssistantMessage:n.lastAssistantMessage})).digest("hex")}let r=e.toolUseId;return typeof r=="string"&&$m.test(r)?`${(0,Qo.createHash)("sha256").update(e.contentSessionId).update("\0").update(Y(e.platformSource)).digest("hex")}-${r}`:(0,Qo.createHash)("sha256").update(t).update("\0").update(e.contentSessionId).update("\0").update(ei(e)).digest("hex")}function Um(t){return typeof t=="string"&&t.length>0}function Su(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(!cR.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"||!Um(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=r.kind;return(s==="observation"||s==="file_edit")&&!Um(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:Y(n.platformSource)},enqueuedAtEpochMs:r.enqueuedAtEpochMs}}function gR(){return yu=Math.max(Date.now(),yu+1),yu}var Qo,re,Ye,cR,uR,$m,lR,dR,Lm,fR,yu,ti,bu=E(()=>{"use strict";Qo=require("crypto"),re=require("fs"),Ye=require("path");oe();N();ut();M();Fm();cR=["observation","file_edit","summarize","session_end","advisor_calls"],uR=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,$m=/^[A-Za-z0-9_-]{1,128}$/,lR="corrupt",dR="expired",Lm=10080*60*1e3,fR=300*1e3;yu=0;ti=class{constructor(e=ri()){this.directory=e}directory;get corruptDirectory(){return(0,Ye.join)(this.directory,lR)}get expiredDirectory(){return(0,Ye.join)(this.directory,dR)}enqueue(e,r,n){let s={...r,platformSource:Y(r.platformSource)},o=(0,Ye.join)(this.directory,`${e}-${pR(e,s)}.json`),i=s.toolUseId;if(typeof i=="string"&&$m.test(i)){let c=(0,Ye.join)(this.directory,`${e}-${i}.json`);try{let u=Su((0,re.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??gR();return $(o,{kind:e,payload:s,enqueuedAtEpochMs:a},{mode:384}),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()-Lm);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,fR,"unknown-session grace window")?a++:i++;continue}if(!h){this.expireIfPastWindow(u,Lm,"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,re.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,re.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,re.renameSync)(e.path,(0,Ye.join)(this.expiredDirectory,e.filename))}catch(i){return i.code==="ENOENT"?!0:(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,re.existsSync)(e))return null;try{let r=Su((0,re.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,Ye.join)(this.directory,e);try{return(0,re.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,re.renameSync)(n,(0,Ye.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:r,corruptDirectory:this.corruptDirectory}),!0}catch(s){return s.code==="ENOENT"?!0:(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,re.existsSync)(this.directory))return{files:[],quarantined:0};let e;try{e=(0,re.readdirSync)(this.directory).filter(s=>uR.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,Ye.join)(this.directory,s),i;try{i=(0,re.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=Su(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 Hm={};Ls(Hm,{SPOOL_NUDGE_TIMEOUT_MS:()=>Bm,nudgeWorkerToDrainHookSpool:()=>Wm,settleHookSpoolNudges:()=>mR,spoolHookEvent:()=>qe});function Wm(){if($n)return $n;let t=(async()=>{try{await(await be("/api/spool/nudge",{method:"POST",timeoutMs:Bm})).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 $n=t,wu.add(t),t.finally(()=>{wu.delete(t),$n===t&&($n=null)}),t}async function mR(){await Promise.all([...wu])}function qe(t,e,r){let n=new ti().enqueue(t,e,r);return f.debug("HOOK","Hook event spooled for the worker",{kind:t,entryPath:n}),Wm(),n}var Bm,wu,$n,$r=E(()=>{"use strict";bu();xt();M();Bm=250,wu=new Set,$n=null});function Xm(t){let e=(t??"").trim();return e?e.slice(0,hR):null}function TR(t){let e=Dt.default.resolve(t);for(let r=0;r<yR;r++){let n=Dt.default.join(e,".git");if((0,ne.existsSync)(n)){try{if((0,ne.statSync)(n).isDirectory())return n;let o=(0,ne.readFileSync)(n,"utf8").match(/^gitdir:\s*(.+)$/m);if(o)return Dt.default.resolve(e,o[1].trim())}catch{return null}return null}let s=Dt.default.dirname(e);if(s===e)return null;e=s}return null}function IR(t){let e=t.trim();if(e.startsWith(jm))return Xm(e.slice(jm.length));if(bR.test(e))return null}function vR(t){try{return IR((0,ne.readFileSync)(Dt.default.join(t,"HEAD"),"utf8"))}catch{return}}function RR(t){let e=Tn(t,["rev-parse","--abbrev-ref","HEAD"],SR);return e.status!==0||!e.stdout||e.stdout==="HEAD"?null:Xm(e.stdout)}function Tu(t,e){let r;try{r=(0,ne.openSync)(Dt.default.join(t,"logs","HEAD"),"r");let n=(0,ne.fstatSync)(r).size,s=Buffer.alloc(Math.min(n,wR));(0,ne.readSync)(r,s,0,s.length,n-s.length);let o=F.loadFromFile(V,!0,{readOnly:!0}),i=Number(o.MEMINDEX_BRANCH_ACTIVE_DAYS),a=Number.isSafeInteger(i)&&i>0?i:14;for(let c of s.toString("utf8").trimEnd().split(`
24
+ `).reverse()){let u=/ (\d+) [+-]\d{4}(?:\t|$)/.exec(c);if(!u)return!1;let l=Number(u[1])*1e3;if(l<=e)return e-l<a*864e5}return!1}catch{return!1}finally{r!==void 0&&(0,ne.closeSync)(r)}}function Km(t,e=Date.now()){if(!t||!Dt.default.isAbsolute(t))return null;let r=TR(t);if(!r)return null;let n=vR(r);if(n!==void 0)return n&&Tu(r,e)?n:null;let s=ni.get(t);if(s&&e-s.at<_R)return s.branch&&Tu(r,e)?s.branch:null;let o=RR(t);return ni.size>=ER&&ni.clear(),ni.set(t,{at:e,branch:o}),o&&Tu(r,e)?o:null}var ne,Dt,hR,_R,ER,SR,yR,jm,bR,wR,ni,Gm=E(()=>{"use strict";ne=require("fs"),Dt=_e(require("path"),1);wo();Ie();N();hR=255,_R=5e3,ER=200,SR=1e3,yR=64,jm="ref: refs/heads/",bR=/^[0-9a-f]{40}([0-9a-f]{24})?$/,wR=8192,ni=new Map});function AR(t=z()){return t.MEMINDEX_BRANCH_MEMORY_ENABLED!=="false"&&t.MEMINDEX_SEND_BRANCH_TO_HOSTING!=="false"}function si(t){if(!AR())return{};let e=Km(t);return e?{branch:e}:{}}var Iu=E(()=>{"use strict";Gm();st();Ie();N()});function Ft(t,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(t.toLowerCase()):!1}var Bn=E(()=>{"use strict"});function eh(t,e){return!!t&&!!e}var th=E(()=>{"use strict"});function NR(t){return new Set((t??"").split(",").map(e=>e.trim()).filter(Boolean))}function Wr(t,e,r){return eh(t,e)?r.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&NR(r.MEMINDEX_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:rh:rh}var rh,ii=E(()=>{"use strict";th();rh={skip:!1}});var nE,sE=E(()=>{nE=(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 jt,Ol=E(()=>{jt="1.10.0"});function BO(t){let e=new Set([t]),r=new Set,n=t.match(oE);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(oE);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 oE,iE,aE=E(()=>{Ol();oE=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;iE=BO(jt)});function HO(){return Object.defineProperty({},"version",{value:jt,enumerable:!0,writable:!1,configurable:!1})}function Fe(t,e,r,n=!1){var s;let o=Gi[Ki]=(s=Gi[Ki])!==null&&s!==void 0?s:HO();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${jt}`);return r.error(i.stack||i.message),!1}return o[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${jt}.`),!0}function ge(t){let e=Gi[Ki];if(e!=null){if(e!==cE){if(!e.version||!iE(e.version))return;cE=e}return e[t]}}function Le(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${jt}.`);let r=Gi[Ki];r&&delete r[t]}var WO,Ki,Gi,cE,Xt=E(()=>{Ol();aE();WO=jt.split(".")[0],Ki=Symbol.for(`opentelemetry.js.api.${WO}`),Gi=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function ys(t,e,r){let n=ge("diag");if(n)return n[t](e,...r)}var uE,lE=E(()=>{Xt();uE=class{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return ys("debug",this._namespace,t)}error(...t){return ys("error",this._namespace,t)}info(...t){return ys("info",this._namespace,t)}warn(...t){return ys("warn",this._namespace,t)}verbose(...t){return ys("verbose",this._namespace,t)}}});function dE(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 fE=E(()=>{});var jO,J,Kt=E(()=>{Xt();lE();fE();jO="diag",J=class pE{static instance(){return this._instance||(this._instance=new pE),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=dE((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 Fe("diag",u,r,!0)};r.setLogger=n,r.disable=()=>{Le(jO,r)},r.createComponentLogger=s=>new uE(s),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}}});var gE,mE=E(()=>{gE=class bs{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 bs(this._entries);return n._entries.set(e,r),n}removeEntry(e){let r=new bs(this._entries);return r._entries.delete(e),r}removeEntries(...e){let r=new bs(this._entries);for(let n of e)r._entries.delete(n);return r}clear(){return new bs}}});var hE,_E=E(()=>{hE=Symbol("BaggageEntryMetadata")});function EE(t={}){return new gE(new Map(Object.entries(t)))}function SE(t){return typeof t!="string"&&(XO.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:hE,toString(){return t}}}var XO,Pl=E(()=>{Kt();mE();_E();XO=J.instance()});function tn(t){return Symbol.for(t)}var zi,ws=E(()=>{zi=new class kl{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 kl(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=n=>{let s=new kl(r._currentContext);return s._currentContext.delete(n),s}}}});var xl,Nl,yE,bE=E(()=>{xl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],Nl={};if(typeof console<"u")for(let t of["error","warn","info","debug","trace","log"])typeof console[t]=="function"&&(Nl[t]=console[t]);yE=class{constructor(){function t(e){return function(...r){let n=Nl[e];if(typeof n!="function"&&(n=Nl.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<xl.length;e++)this[xl[e].n]=t(xl[e].c)}}});function wE(){return Dl}var KO,Vi,GO,zO,VO,YO,Cl,qO,JO,ZO,Dl,QO,eP,tP,rP,nP,sP,oP,Fl=E(()=>{KO=class{constructor(){}createGauge(t,e){return eP}createHistogram(t,e){return tP}createCounter(t,e){return QO}createUpDownCounter(t,e){return rP}createObservableGauge(t,e){return sP}createObservableCounter(t,e){return nP}createObservableUpDownCounter(t,e){return oP}addBatchObservableCallback(t,e){}removeBatchObservableCallback(t){}},Vi=class{},GO=class extends Vi{add(t,e){}},zO=class extends Vi{add(t,e){}},VO=class extends Vi{record(t,e){}},YO=class extends Vi{record(t,e){}},Cl=class{addCallback(t){}removeCallback(t){}},qO=class extends Cl{},JO=class extends Cl{},ZO=class extends Cl{},Dl=new KO,QO=new GO,eP=new VO,tP=new YO,rP=new zO,nP=new qO,sP=new JO,oP=new ZO});var TE,IE=E(()=>{TE=(function(t){return t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE",t})({})});function vE(){return Ul}var Ll,Ul,Yi=E(()=>{Ll=class{emit(t){}enabled(){return!1}},Ul=new Ll});var RE,AE=E(()=>{RE=(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 qi,Ji,$l=E(()=>{qi={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},Ji={set(t,e,r){t!=null&&(t[e]=r)}}});var ME,OE=E(()=>{ME=(function(t){return t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED",t})({})});var Bl,Wl,Zi,Hl=E(()=>{Bl="0000000000000000",Wl="00000000000000000000000000000000",Zi={traceId:Wl,spanId:Bl,traceFlags:0}});var Gt,Qi=E(()=>{Hl();Gt=class{constructor(t=Zi){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 PE(t,e){if(typeof t!="string"||t.length!==e)return!1;let r=0;for(let n=0;n<t.length;n+=4)r+=(ea[t.charCodeAt(n)]|0)+(ea[t.charCodeAt(n+1)]|0)+(ea[t.charCodeAt(n+2)]|0)+(ea[t.charCodeAt(n+3)]|0);return r===e}function jl(t){return PE(t,32)&&t!=="00000000000000000000000000000000"}function Xl(t){return PE(t,16)&&t!=="0000000000000000"}function rn(t){return jl(t.traceId)&&Xl(t.spanId)}function kE(t){return new Gt(t)}var ea,ta=E(()=>{Qi();ea=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 xE,NE=E(()=>{ws();xE=class{active(){return zi}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 Kl,iP,aP,zt,Ts=E(()=>{Xt();Kt();NE();Kl="context",iP=new xE,aP=Object.freeze({dispose:()=>{}}),zt=class CE{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new CE),this._instance}setGlobalContextManager(e){return Fe(Kl,e,J.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,J.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.")),aP)}_getContextManager(){return ge(Kl)||iP}disable(){this._getContextManager().disable(),Le(Kl,J.instance())}}});function ra(t){return t.getValue(Gl)||void 0}function DE(){return ra(zt.getInstance().active())}function Is(t,e){return t.setValue(Gl,e)}function FE(t){return t.deleteValue(Gl)}function LE(t,e){return Is(t,new Gt(e))}function na(t){var e;return(e=ra(t))===null||e===void 0?void 0:e.spanContext()}var Gl,zl=E(()=>{ws();Ts();Qi();Gl=tn("OpenTelemetry Context Key SPAN")});function cP(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 Vl,sa,Yl=E(()=>{Ts();Qi();zl();ta();Vl=zt.getInstance(),sa=class{startSpan(t,e,r=Vl.active()){if(e?.root)return new Gt;let n=r&&na(r);return cP(n)&&rn(n)?new Gt(n):new Gt}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:Vl.active(),u=this.startSpan(t,o,c),l=Is(c,u);return Vl.with(l,a,void 0,u)}}});var uP,oa,ql=E(()=>{Yl();uP=new sa,oa=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):uP}}});var UE,$E=E(()=>{UE=(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 BE,WE=E(()=>{BE=(function(t){return t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR",t})({})});function HE(t){return lP.test(t)}function jE(t){return dP.test(t)&&!fP.test(t)}var Jl,lP,dP,fP,XE=E(()=>{Jl="[_0-9a-z-*/]",lP=new RegExp(`^(?:${`[a-z]${Jl}{0,255}`}|${`[a-z0-9]${Jl}{0,240}@[a-z]${Jl}{0,13}`})$`),dP=/^[ -~]{0,255}[!-~]$/,fP=/,|=/});var Zl,KE,GE,zE,VE,qE=E(()=>{XE();Zl=32,KE=512,GE=",",zE="=",VE=class YE{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>=Zl)return this;s+=e.length+r.length+(this._internalState.size>0?2:1)}if(s>KE)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+zE+this.get(r)),e),[]).join(GE)}_parse(e){e.length>KE||(this._internalState=e.split(GE).reduceRight((r,n)=>{let s=n.trim(),o=s.indexOf(zE);if(o!==-1){let i=s.slice(0,o),a=s.slice(o+1,n.length);HE(i)&&jE(a)&&r.set(i,a)}return r},new Map),this._internalState.size>Zl&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Zl))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new YE;return e._internalState=new Map(this._internalState),e}}});function JE(t){return new VE(t)}var ZE=E(()=>{qE()});var QE,eS=E(()=>{Yl();QE=class{getTracer(t,e,r){return new sa}}});var pP,vs,Ql=E(()=>{ql();eS();pP=new QE,vs=class{getTracer(t,e,r){var n;return(n=this.getDelegateTracer(t,e,r))!==null&&n!==void 0?n:new oa(this,t,e,r)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:pP}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 tS,rS=E(()=>{tS=(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 ed,nS=E(()=>{Ts();ed=zt.getInstance()});var td,sS=E(()=>{Kt();td=J.instance()});var gP,oS,iS=E(()=>{Yi();gP=class{getLogger(t,e,r){return new Ll}},oS=new gP});var aS,cS=E(()=>{Yi();aS=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):Ul}}});var rd,uS=E(()=>{iS();cS();rd=class{getLogger(t,e,r){var n;return(n=this._getDelegateLogger(t,e,r))!==null&&n!==void 0?n:new aS(this,t,e,r)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:oS}_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 nd,lS,fS=E(()=>{Xt();Kt();uS();nd="logs",lS=class dS{constructor(){this._proxyLoggerProvider=new rd}static getInstance(){return this._instance||(this._instance=new dS),this._instance}setGlobalLoggerProvider(e){let r=Fe(nd,e,J.instance());return r&&this._proxyLoggerProvider._setDelegate(e),r}getLoggerProvider(){return ge(nd)||this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){Le(nd,J.instance()),this._proxyLoggerProvider=new rd}}});var sd,pS=E(()=>{fS();sd=lS.getInstance()});var mP,gS,mS=E(()=>{Fl();mP=class{getMeter(t,e,r){return Dl}},gS=new mP});var od,hS,ES=E(()=>{Xt();Kt();mS();od="metrics",hS=class _S{constructor(){}static getInstance(){return this._instance||(this._instance=new _S),this._instance}setGlobalMeterProvider(e){return Fe(od,e,J.instance())}getMeterProvider(){return ge(od)||gS}getMeter(e,r,n){return this.getMeterProvider().getMeter(e,r,n)}disable(){Le(od,J.instance())}}});var id,SS=E(()=>{ES();id=hS.getInstance()});var yS,bS=E(()=>{yS=class{inject(t,e){}extract(t,e){return t}fields(){return[]}}});function cd(t){return t.getValue(ad)||void 0}function wS(){return cd(zt.getInstance().active())}function TS(t,e){return t.setValue(ad,e)}function IS(t){return t.deleteValue(ad)}var ad,vS=E(()=>{ws();Ts();ad=tn("OpenTelemetry Baggage Key")});var ud,hP,RS,MS=E(()=>{Xt();Kt();Pl();$l();bS();vS();ud="propagation",hP=new yS,RS=class AS{constructor(){this.createBaggage=EE,this.getBaggage=cd,this.getActiveBaggage=wS,this.setBaggage=TS,this.deleteBaggage=IS}static getInstance(){return this._instance||(this._instance=new AS),this._instance}setGlobalPropagator(e){return Fe(ud,e,J.instance())}inject(e,r,n=Ji){return this._getGlobalPropagator().inject(e,r,n)}extract(e,r,n=qi){return this._getGlobalPropagator().extract(e,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){Le(ud,J.instance())}_getGlobalPropagator(){return ge(ud)||hP}}});var ld,OS=E(()=>{MS();ld=RS.getInstance()});var dd,PS,xS=E(()=>{Xt();Kt();zl();ta();Ql();dd="trace",PS=class kS{constructor(){this._proxyTracerProvider=new vs,this.wrapSpanContext=kE,this.isSpanContextValid=rn,this.deleteSpan=FE,this.getSpan=ra,this.getActiveSpan=DE,this.getSpanContext=na,this.setSpan=Is,this.setSpanContext=LE}static getInstance(){return this._instance||(this._instance=new kS),this._instance}setGlobalTracerProvider(e){let r=Fe(dd,this._proxyTracerProvider,J.instance());return r&&this._proxyTracerProvider.setDelegate(e),r}getTracerProvider(){return ge(dd)||this._proxyTracerProvider}getTracer(e,r){return this.getTracerProvider().getTracer(e,r)}disable(){Le(dd,J.instance()),this._proxyTracerProvider=new vs}}});var fd,NS=E(()=>{xS();fd=PS.getInstance()});var CS={};Ls(CS,{DiagConsoleLogger:()=>yE,DiagLogLevel:()=>nE,INVALID_SPANID:()=>Bl,INVALID_SPAN_CONTEXT:()=>Zi,INVALID_TRACEID:()=>Wl,ProxyTracer:()=>oa,ProxyTracerProvider:()=>vs,ROOT_CONTEXT:()=>zi,SamplingDecision:()=>tS,SeverityNumber:()=>RE,SpanKind:()=>UE,SpanStatusCode:()=>BE,TraceFlags:()=>ME,ValueType:()=>TE,baggageEntryMetadataFromString:()=>SE,context:()=>ed,createContextKey:()=>tn,createNoopLogger:()=>vE,createNoopMeter:()=>wE,createTraceState:()=>JE,default:()=>_P,defaultTextMapGetter:()=>qi,defaultTextMapSetter:()=>Ji,diag:()=>td,isSpanContextValid:()=>rn,isValidSpanId:()=>Xl,isValidTraceId:()=>jl,logs:()=>sd,metrics:()=>id,propagation:()=>ld,trace:()=>fd});var _P,DS=E(()=>{sE();Pl();ws();bE();Fl();IE();Yi();AE();$l();OE();Hl();ta();ql();$E();WE();ZE();Ql();rS();nS();sS();pS();SS();OS();NS();_P={context:ed,diag:td,logs:sd,metrics:id,propagation:ld,trace:fd}});function ny(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 sn(t){if(!t)return!1;if(t.startsWith("memory_")||t==="mem_search"||t==="get_summaries")return!0;let e=ny(t);return e!==null&&dk.has(e)}function _a(t){return t==="save_memory"||ny(t)==="save_memory"}var dk,Ea=E(()=>{"use strict";dk=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 Td(t){return typeof t=="string"&&t.length>0}var Ns,by=E(()=>{"use strict";Ns=class extends Error{constructor(r){super(`adapter rejected input: ${r}`);this.reason=r;this.name="AdapterRejectedInput"}reason}});var Pk,wy,Id,kk,xk,Ty,Iy=E(()=>{"use strict";by();nr();Pk=128,wy=t=>typeof t=="string"&&t.length>0&&t.length<=Pk?t:void 0,Id=t=>typeof t=="string"?t:void 0,kk=t=>t.hook_event_name==="PostToolUseFailure"?{error:t.error,is_interrupt:t.is_interrupt===!0}:void 0,xk=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},Ty={normalizeInput(t){let e=t??{},r=e.cwd??process.cwd();if(!Td(r))throw new Ns("invalid_cwd");let n=Fp(r);if(!Td(n))throw new Ns("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:xk(e),toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response??kk(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:wy(e.agent_id),agentType:wy(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 vy(t,e){return qe("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 Ry,Ay=E(()=>{"use strict";$r();M();rt();Dr();ii();st();Iu();Bn();ut();Fr();cr();Un();Ea();Ry={async execute(t){let{sessionId:e,cwd:r,toolName:n,toolInput:s,toolResponse:o}=t,i=Y(t.platform);if(!n)return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(sn(n))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(f.dataIn("HOOK",`PostToolUse: ${n}`,{}),!r)throw new Error(`Missing cwd in PostToolUse hook input for session ${e}, tool ${n}`);if(!ct(r))return f.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:r,toolName:n}),{continue:!0,suppressOutput:!0};let a=Wr(t.agentId,t.agentType,z());if(a.skip)return f.debug("HOOK",`Skipping observation: ${a.reason}`,{toolName:n,agentId:t.agentId,agentType:t.agentType}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(_a(n))return vy(t,i);let c=Ge();if(c.runtime==="server"){if(Ft(n,z().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 u={projectId:c.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},...si(r)};try{return await c.client.recordEvent(u),f.debug("HOOK","Observation sent successfully via server",{toolName:n}),await Lr(c.client,Ve(c)),{continue:!0,suppressOutput:!0}}catch(l){if(yt(l))return ze(l.kind,{status:l.status,message:l.message,route:"/v1/events",held:!0}),Ct({op:"event",request:u},Ve(c)),{continue:!0,suppressOutput:!0};if(Ke(l)&&l.isFallbackEligible())ze(l.kind,{status:l.status,message:l.message,route:"/v1/events"});else return f.error("HOOK","Server event failed (non-recoverable)",{error:l instanceof Error?l.message:String(l)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}return vy(t,i)}}});function Dk(t,e,r){let n=0;for(;n<e.length;){let s=(0,Qe.readSync)(t,e,n,e.length-n,r+n);if(s===0)break;n+=s}return n}function*Fk(t,e){let r=Math.max(1,e.maxChunkBytes??My),n=Math.min(r,Math.max(1,e.initialBytes??Nk)),s=(0,Qe.openSync)(t,"r");try{let o=(0,Qe.fstatSync)(s).size,i=Buffer.alloc(0);for(;o>0;){let a=Math.max(0,o-n),c=Buffer.alloc(o-a),u=Dk(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,Qe.closeSync)(s)}}function Oy(t,e,r={}){if(!t||!(0,Qe.existsSync)(t)){f.warn("PARSER",`Transcript path missing or file does not exist: ${t}`);return}let n=!1;for(let s of Fk(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*vd(t){let e=t.split(`
25
+ `);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 Lk(t,e,r,n,s){let o,i=null,a,c,u=!1,l=0,d=Math.max(0,s?.modelSearchBudgetBytes??Ck),p=Oy(t,(g,m,h)=>{if(s?.includeTurnId&&!u)for(let b of vd(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=xy(g)),o===void 0){let b=jk(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 Rd(t,e=!1,r){let n=Lk(t,"assistant",e,!0,r);return{text:n.text,...n.model===void 0?{}:{model:n.model},...n.turnId===void 0?{}:{turnId:n.turnId}}}function Py(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(`
26
+ `):null}function Bk(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 Wk(t,e){if(e==="user"&&t?.type==="context.append_message")return Py(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 Hk(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 jk(t,e,r){let n=!1,s=null,o="blank";for(let i of vd(t)){let a=Bk(i),c=typeof i.type=="string"?Uk[i.type]:void 0,u=typeof i.type=="string"?$k[i.type]:void 0;if((a??c??u??i.type??i.role)!==e)continue;n=!0;let d,p;if(a!==void 0)d=Wk(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=Py(p);if(g===null)continue;d=g}if(r&&(d=zo(d),d=d.replace(/\n{3,}/g,`
27
27
 
28
- `).trim()),d&&d.trim())return{kind:"text",text:d};if(s===null&&(s=d,!s.trim()&&Array.isArray(p))){let g=jk(p);g&&(s=g,o="synthesized")}}return n?{kind:o,text:s??""}:{kind:"none",text:""}}function Oy(t,e){if(!(!t||!(0,Qe.existsSync)(t)))return Ay(t,r=>Py(r),e)}function Py(t){for(let e of vd(t)){if((e.type??e.role)!=="assistant")continue;let r=e.message?.model;if(typeof r=="string"&&r)return r}}var Qe,Nk,Ry,Ck,Uk,$k,ky=E(()=>{"use strict";Qe=require("fs");M();lt();Nk=256*1024,Ry=64*1024*1024,Ck=Ry;Uk={USER_INPUT:"user",PLANNER_RESPONSE:"assistant"},$k={"user.message":"user","assistant.message":"assistant"}});function Kk(t){return Xk.has(t)}function Gk(t=process.env){return t.CLAUDE_CONFIG_DIR?(0,Ad.join)(t.CLAUDE_CONFIG_DIR,".claude.json"):(0,Ad.join)((0,xy.homedir)(),".claude.json")}function va(t){if(!t)return!1;let e=t.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"}function zk(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 Vk(t){if(!(0,Ra.existsSync)(t))return{};let e;try{e=Jt((0,Ra.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 zk(e)}function Yk(t,e){let r=t.customApiKeyResponses?.approved;return Array.isArray(r)&&r.includes(e.slice(-20))}function qk(t){let e=t.oauthAccount?.organizationType;if(typeof e!="string")return;let r=e.replace(/^claude_/,"");return Kk(r)?r:"subscription"}function Ny(t=process.env,e=Gk(t)){if(va(t.CLAUDE_CODE_USE_BEDROCK))return"bedrock";if(va(t.CLAUDE_CODE_USE_VERTEX))return"vertex";if(va(t.CLAUDE_CODE_USE_FOUNDRY))return"foundry";let r=Vk(e),n=!!r.oauthAccount,s=t.ANTHROPIC_API_KEY||t.ANTHROPIC_AUTH_TOKEN;if(s&&(!n||Yk(r,s)))return"api_key";let o=qk(r);return o||(n||va(t.CLAUDE_CODE_OAUTH_TOKEN)?"subscription":"unknown")}var Ra,Ad,xy,Xk,Cy=E(()=>{"use strict";Ra=require("fs"),Ad=require("path"),xy=require("os");M();oe();Xk=new Set(["max","pro","team","enterprise"])});function Qk(t){let e=Zk.test(t)?t:`sha256-${(0,Dy.createHash)("sha256").update(t).digest("hex")}`;return(0,Md.join)(x(),"state",Jk,e)}function Fy(t){try{(0,Ds.rmSync)(Qk(t),{force:!0})}catch(e){f.warn("HOOK","kimi-context-gate: clearInjected failed open",{error:e instanceof Error?e.message:String(e)})}}var Ds,Dy,Md,Jk,Zk,Ly=E(()=>{"use strict";Ds=require("fs"),Dy=require("crypto"),Md=require("path");N();M();Jk="kimi-context-injected",Zk=/^[A-Za-z0-9_-]{1,128}$/});function t0(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(`
29
- `):""}function Uy(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function r0(t,e){let r=(0,et.openSync)(t,"r");try{let n=(0,et.fstatSync)(r).size,s=Math.max(0,n-e),o=Buffer.alloc(n-s);if((0,et.readSync)(r,o,0,o.length,s),s===0)return{text:o.toString("utf-8"),startOffset:0};let i=Buffer.alloc(1);if((0,et.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,et.closeSync)(r)}}function $y(t,e={}){if(!t||!(0,et.existsSync)(t))return[];let{text:r,startOffset:n}=r0(t,e.maxTailBytes??e0);return r.trim()?n0(r,e,n):[]}function n0(t,e={},r=0){let n=t.split(`
28
+ `).trim()),d&&d.trim())return{kind:"text",text:d};if(s===null&&(s=d,!s.trim()&&Array.isArray(p))){let g=Hk(p);g&&(s=g,o="synthesized")}}return n?{kind:o,text:s??""}:{kind:"none",text:""}}function ky(t,e){if(!(!t||!(0,Qe.existsSync)(t)))return Oy(t,r=>xy(r),e)}function xy(t){for(let e of vd(t)){if((e.type??e.role)!=="assistant")continue;let r=e.message?.model;if(typeof r=="string"&&r)return r}}var Qe,Nk,My,Ck,Uk,$k,Ny=E(()=>{"use strict";Qe=require("fs");M();lt();Nk=256*1024,My=64*1024*1024,Ck=My;Uk={USER_INPUT:"user",PLANNER_RESPONSE:"assistant"},$k={"user.message":"user","assistant.message":"assistant"}});function Kk(t){return Xk.has(t)}function Gk(t=process.env){return t.CLAUDE_CONFIG_DIR?(0,Ad.join)(t.CLAUDE_CONFIG_DIR,".claude.json"):(0,Ad.join)((0,Cy.homedir)(),".claude.json")}function va(t){if(!t)return!1;let e=t.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"}function zk(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 Vk(t){if(!(0,Ra.existsSync)(t))return{};let e;try{e=Jt((0,Ra.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 zk(e)}function Yk(t,e){let r=t.customApiKeyResponses?.approved;return Array.isArray(r)&&r.includes(e.slice(-20))}function qk(t){let e=t.oauthAccount?.organizationType;if(typeof e!="string")return;let r=e.replace(/^claude_/,"");return Kk(r)?r:"subscription"}function Dy(t=process.env,e=Gk(t)){if(va(t.CLAUDE_CODE_USE_BEDROCK))return"bedrock";if(va(t.CLAUDE_CODE_USE_VERTEX))return"vertex";if(va(t.CLAUDE_CODE_USE_FOUNDRY))return"foundry";let r=Vk(e),n=!!r.oauthAccount,s=t.ANTHROPIC_API_KEY||t.ANTHROPIC_AUTH_TOKEN;if(s&&(!n||Yk(r,s)))return"api_key";let o=qk(r);return o||(n||va(t.CLAUDE_CODE_OAUTH_TOKEN)?"subscription":"unknown")}var Ra,Ad,Cy,Xk,Fy=E(()=>{"use strict";Ra=require("fs"),Ad=require("path"),Cy=require("os");M();oe();Xk=new Set(["max","pro","team","enterprise"])});function Qk(t){let e=Zk.test(t)?t:`sha256-${(0,Ly.createHash)("sha256").update(t).digest("hex")}`;return(0,Md.join)(x(),"state",Jk,e)}function Uy(t){try{(0,Cs.rmSync)(Qk(t),{force:!0})}catch(e){f.warn("HOOK","kimi-context-gate: clearInjected failed open",{error:e instanceof Error?e.message:String(e)})}}var Cs,Ly,Md,Jk,Zk,$y=E(()=>{"use strict";Cs=require("fs"),Ly=require("crypto"),Md=require("path");N();M();Jk="kimi-context-injected",Zk=/^[A-Za-z0-9_-]{1,128}$/});function t0(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(`
29
+ `):""}function By(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function r0(t,e){let r=(0,et.openSync)(t,"r");try{let n=(0,et.fstatSync)(r).size,s=Math.max(0,n-e),o=Buffer.alloc(n-s);if((0,et.readSync)(r,o,0,o.length,s),s===0)return{text:o.toString("utf-8"),startOffset:0};let i=Buffer.alloc(1);if((0,et.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,et.closeSync)(r)}}function Wy(t,e={}){if(!t||!(0,et.existsSync)(t))return[];let{text:r,startOffset:n}=r0(t,e.maxTailBytes??e0);return r.trim()?n0(r,e,n):[]}function n0(t,e={},r=0){let n=t.split(`
30
30
  `),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=zo(t0(m)).replace(/\n{3,}/g,`
31
31
 
32
- `).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:Uy(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 w=typeof S.text=="string"?S.text.trim():"";if(!w)continue;a.push({call:{toolUseId:h.tool_use_id,advisorModel:_.advisorModel,advice:w,occurredAtEpoch:_.occurredAtEpoch||(Uy(p.timestamp)??Date.now()),transcriptByteOffset:_.transcriptByteOffset,lastUserMessage:_.lastUserMessage},userTurnLine:_.userTurnLine})}}}}return a.filter(u=>!e.currentTurnOnly||u.userTurnLine===o).map(u=>u.call)}var et,e0,By=E(()=>{"use strict";et=require("fs");lt();e0=2*1024*1024});function o0(t,e,r,n){if(!e||z().MEMINDEX_CAPTURE_ADVISOR_CALLS!=="true"||Ge().runtime==="server")return;let s=$y(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+=Wy)qe("advisor_calls",{contentSessionId:t,platformSource:n,cwd:r,transcriptPath:e,calls:s.slice(o,o+Wy).map(i=>({toolUseId:i.toolUseId,advice:i.advice,advisorModel:i.advisorModel,occurredAtEpoch:i.occurredAtEpoch,lastUserMessage:i.lastUserMessage,transcriptByteOffset:i.transcriptByteOffset}))})}}async function i0(t,e,r){return await hu(t.client,e,void 0,r),f.debug("HOOK","Summary request queued via server"),await Lr(t.client,Ve(t)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}var jy,Hy,Wy,Xy,Ky=E(()=>{"use strict";$r();M();ky();jy=require("crypto"),Hy=require("path");Cy();lt();rt();xt();ut();Dr();Ly();Fr();cr();$n();By();st();Wy=50;Xy={async execute(t){if(t.cwd&&!ct(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"&&Fy(e);try{o0(e,r,t.cwd,Y(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=we(t.lastAssistantMessage);try{if(r&&t.platform==="claude-code"&&!o){let d=Rd(r,!0,i);s=d.model,o=d.turnId}else s=r?Oy(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=Rd(r,!0,i);n=we(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=Y(t.platform),c=t.platform==="claude-code"?Ny():void 0,u=Ge();if(u.runtime==="server"){let d={projectId:u.projectId,contentSessionId:e,platformSource:a,lastAssistantMessage:n,occurredAtEpoch:Date.now()},p=d;try{return await i0(u,d,g=>{p=g})}catch(g){if(yt(g))return ze(g.kind,{status:g.status,message:g.message,route:"/v1/sessions/end",held:!0}),Ct({op:"summarize",request:p},Ve(u)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(Ke(g)&&g.isFallbackEligible())ze(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,jy.randomUUID)());let l=qe("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 be("/api/spool/nudge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({waitForSummary:!0,contentSessionId:e,platformSource:a,captureKey:(0,Hy.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 Gy=E(()=>{"use strict"});function zy(t){let e=we(t).trim();return e.length<=Od?e:(f.debug("DB","Truncated stored prompt text to the configured cap",{originalLength:e.length,storedLength:Od}),`${e.slice(0,Od-1)}\u2026`)}var Od,Pd,Vy=E(()=>{"use strict";lt();M();Od=4e3,Pd="[media prompt]"});function a0(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function Qy(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>vt(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
33
- `):""}function l0(t){if(t.type!=="user"||t.isSidechain===!0||t.isMeta===!0||t.isCompactSummary===!0)return null;let e=vt(t.message)?t.message:null;if(!e)return null;let r=e.content;if(Array.isArray(r)&&r.some(i=>vt(i)&&i.type==="tool_result"))return null;let n=vt(t.origin)?t.origin:null;if(n){if(n.kind!=="human")return null}else if(typeof t.promptSource=="string"&&!u0.has(t.promptSource))return null;let s=Qy(r),o=s.trimStart();return!n&&c0.some(i=>o.startsWith(i))||!s.trim()&&!Array.isArray(r)?null:s}function d0(t){return typeof t=="string"?t:Qy(t)}async function*f0(t){let e=(0,Zy.createInterface)({input:(0,tt.createReadStream)(t,{encoding:"utf8"}),crlfDelay:1/0});for await(let r of e)if(r.trim())try{let n=JSON.parse(r);vt(n)&&(yield n)}catch{}}async function Yy(t,e={}){let r=[],n=new Map,s=null,o=e.agentId!==void 0,i=0;for await(let a of f0(t)){i++,s===null&&typeof a.cwd=="string"&&a.cwd.trim()&&(s=a.cwd);let c=a0(a.timestamp),u=vt(a.message)?a.message:null;if(a.type==="assistant"&&u&&Array.isArray(u.content)){for(let l of u.content)vt(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(!vt(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=d0(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=l0(a);if(l!==null){let d=typeof a.uuid=="string"&&a.uuid?a.uuid:`${(0,Vt.basename)(t)}:${i}`;r.push({kind:"prompt",timestampMs:c,uuid:d,text:l})}}}}return{events:r,firstCwd:s}}function p0(t){try{let e=JSON.parse((0,tt.readFileSync)(t,"utf8"));return vt(e)&&typeof e.agentType=="string"&&e.agentType?e.agentType:void 0}catch{return}}async function eb(t,e){let r=await Yy(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,Vt.basename)(a,".jsonl").replace(/^agent-/,""),u=p0(a.replace(/\.jsonl$/,".meta.json"));(await Yy(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 qy(t){try{return(0,tt.statSync)(t).mtimeMs}catch{return 0}}function kd(t){try{return(0,tt.readdirSync)(t)}catch{return[]}}function Jy(t){let e=[];for(let r of kd(t).sort()){let n=g0.exec(r);if(!n)continue;let s=n[1],o=(0,Vt.join)(t,r),i=(0,Vt.join)(t,s,"subagents"),a=(0,tt.existsSync)(i)?kd(i).filter(u=>u.startsWith("agent-")&&u.endsWith(".jsonl")).sort().map(u=>(0,Vt.join)(i,u)):[],c=Math.max(qy(o),...a.map(qy));e.push({sessionId:s,transcriptPath:o,subagentPaths:a,lastModifiedMs:c})}return e}function tb(t){let e=Jy(t);return e.length>0?e:kd(t).sort().map(r=>(0,Vt.join)(t,r)).filter(r=>{try{return(0,tt.statSync)(r).isDirectory()}catch{return!1}}).flatMap(Jy)}var tt,Vt,Zy,vt,c0,u0,g0,rb=E(()=>{"use strict";tt=require("fs"),Vt=require("path"),Zy=require("readline"),vt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);c0=["<command-name>","<command-message>","<local-command-stdout>","<local-command-stderr>","<local-command-caveat>"],u0=new Set(["typed","queued","sdk"]);g0=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i});var xd=E(()=>{"use strict"});var nb=E(()=>{"use strict";xd()});var sb=E(()=>{"use strict";xd()});var ob,Nd,ib=E(()=>{"use strict";N();ob=require("path");rb();nb();sb();Nd={id:"claude-code",label:"Claude Code",platform:"claude-code",defaultDir:()=>(0,ob.join)(Be,"projects"),find:tb,read:eb}});var fb={};Us(fb,{BACKLOG_HIGH_WATER:()=>Dd,CLAUDE_CODE_PLATFORM:()=>b0,TRANSCRIPT_IMPORT_USAGE:()=>A0,defaultTranscriptImportDeps:()=>db,formatTranscriptImportResult:()=>W0,isPromptSkippedByWorker:()=>Fd,isoOf:()=>Fs,matchRecordedPrompts:()=>ub,parseTranscriptImportArgs:()=>R0,promptKey:()=>an,runTranscriptImport:()=>B0});function R0(t){let e=null,r=null,n=(0,Oa.join)(Be,"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 yr(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 an(t){return zy(we(t.trim()?t:Pd))}function cb(t){let e=t.replace(/\s+/g," ").trim();return e.length>ab?`${e.slice(0,ab-1)}\u2026`:e}function Fs(t){return t===null?"(no time)":new Date(t).toISOString()}function ub(t,e,r){let n=e.map(c=>an(c.text)),s=new Set,o=new Map;for(let c of[...t].reverse()){if(!r.has(c.uuid))continue;let u=an(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=an(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 Cd(t,e){let r=by.normalizeInput(t);return r.platform=e,r}function O0(t){let e=r=>Math.min(M0,(typeof r=="string"?r:JSON.stringify(r??"")).length);return e(t.toolInput)+e(t.failed?t.error:t.toolResponse)}function P0(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 k0(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 x0(t){let e=await t.backlog();if(e===null||e<=Dd)return;let r=Date.now(),n=e,s=0;for(;e!==null&&e>Dd;)if(Date.now()-s>=3e4&&(t.log(` waiting for the worker to catch up (${e} items queued)`),s=Date.now()),await t.sleep(w0),e=await t.backlog(),e!==n)n=e??n,r=Date.now();else if(Date.now()-r>Ma)throw new Error(`the worker has not taken any queued work for ${Math.round(Ma/6e4)} minutes (${e} items queued)`)}function C0(t){let e=0;return{async check(r=!1){e++,!(!r&&e<N0)&&(e=0,await x0(t))}}}async function F0(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(D0),r=t.pendingSpoolFor(e),r!==s)s=r,n=t.now();else if(t.now()-n>Ma)throw new Error(`the worker has not taken this session's queued events for ${Math.round(Ma/6e4)} minutes (${r} waiting)`)}function Fd(t){return Vo(t)||t.trim()!==""&&we(t).trim()===""}async function L0(t,e){for(let r=1;;r++)try{await t.sendPrompt(e);return}catch(n){if(!(n instanceof Ur)||r>=T0)throw n;await t.sleep(I0*r)}}async function $0(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=ub(t.events.filter(I=>I.kind==="prompt"),r.prompts,u),p=t.events.flatMap((I,y)=>I.kind==="prompt"&&d.has(I.uuid)&&!u.has(I.uuid)?[y]:[]),g=r.hasObservations&&r.prompts.length>0&&r.toolUseIds.size===0,m=t.sessionId,h=new Map;for(let I of r.prompts){let y=an(I.text);h.set(y,Math.max(h.get(y)??Number.NEGATIVE_INFINITY,I.createdAtEpochMs))}let _=null,S=0,w=()=>{s.dryRun||(n.prompts=[...u],n.summaries=[...l],o.saveLedger(m,n))},T=()=>{let I=_?.anchor;if(!I)return;let y=I.atEpochMs+1+_.anchored;return y>=I.beforeEpochMs?Math.max(I.atEpochMs,I.beforeEpochMs-1):(_.anchored++,y)},R=async()=>{if(!_?.summaryOwed||!_.last||!yr(_.last.timestampMs,s))return;let I=_.last.text.join(`
34
- `);if(s.dryRun)o.log(` summary ${Fs(_.last.timestampMs)} ${cb(I)}`);else{let y=Cd({session_id:m,cwd:e,hook_event_name:"Stop",last_assistant_message:I},a);y.lastAssistantMessage=I,y.spoolAtEpochMs=T(),y.turnId=_.uuid,await i.check(),await o.sendSummary(y),S++,l.add(_.uuid),w()}c.summaries++,c.summaryChars+=I.length};for(let I=0;I<t.events.length;I++){let y=t.events[I];if(y.kind==="prompt"){await R();let v=an(y.text),A=d.get(y.uuid)??null,b=u.has(y.uuid),P=A?r.prompts.find(Ue=>Ue.createdAtEpochMs>A.createdAtEpochMs):void 0;if(_={uuid:y.uuid,summaryOwed:b&&!l.has(y.uuid),anchor:A?{atEpochMs:A.createdAtEpochMs,beforeEpochMs:P?.createdAtEpochMs??Number.POSITIVE_INFINITY}:null,anchored:0,capturedLive:A!==null&&!b,last:null},A){yr(y.timestampMs,s)&&c.alreadyRecorded++;continue}if(b&&Fd(y.text)){_.skippedByWorker=!0,_.summaryOwed=!1,yr(y.timestampMs,s)&&c.alreadyRecorded++;continue}if(_.summaryOwed=!1,!yr(y.timestampMs,s))continue;if(s.dryRun)o.log(` prompt ${Fs(y.timestampMs)} ${cb(y.text)||Pd}`);else{await i.check(!0);let Ue=(h.get(v)??Number.NEGATIVE_INFINITY)+U0-o.now();Ue>0&&await o.sleep(Ue),S>0&&await F0(o,m),S=0,u.add(y.uuid),w(),await L0(o,Cd({session_id:m,cwd:e,hook_event_name:"UserPromptSubmit",prompt:y.text,transcript_path:t.transcriptPath},a)),h.set(v,o.now())}if(Fd(y.text)){_.skippedByWorker=!0,c.prompts++;continue}p.some(Ue=>Ue>I)&&(c.outOfOrder++,o.log(` note: the prompt at ${Fs(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(yr(y.timestampMs,s)&&!_?.skippedByWorker){if(r.toolUseIds.has(y.toolUseId)||g&&(!_||_.capturedLive)){c.alreadyRecorded++;continue}if(!o.isDropped(y)){if(s.dryRun){let v=y.agentId?` (subagent ${y.agentType??y.agentId})`:"";o.log(` tool use ${Fs(y.timestampMs)} ${y.toolName} ${y.toolUseId}${y.failed?" failed":""}${v}`)}else{let v=Cd(P0(m,e,y),a);v.spoolAtEpochMs=T(),await o.sendToolUse(v),S++,r.toolUseIds.add(y.toolUseId),await i.check()}c.toolUses++,c.toolChars+=O0(y)}}}return await R(),c}async function B0(t,e=db(),r=Nd){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,Yt.existsSync)(t.projectDir))return n.error=`no ${r===Nd?"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=C0(e);for(let a of s){n.sessionsScanned++;let c;try{c=await r.read(a,g=>yr(g,t))}catch(g){e.log(`Skipped ${a.transcriptPath}: ${g instanceof Error?g.message:String(g)}`);continue}if(!c.events.some(g=>yr(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 k0(u,()=>$0(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 W0(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 Aa(t){let e=await be(t,{timeoutMs:v0});if(!e.ok)throw new Error(`${t} answered ${e.status}`);return e.json()}async function j0(t){let e=encodeURIComponent(t);try{let r=[];for(let o=0;;o+=100){let i=await Aa(`/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 Aa(`/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 Aa(`/api/observations?contentSessionId=${e}&limit=1`);return{prompts:r,toolUseIds:n,hasObservations:(s.items?.length??0)>0}}catch{return null}}function lb(t){return(0,Oa.join)(x(),"state","transcript-import",`${t.replace(/[^A-Za-z0-9_-]/g,"_")}.json`)}function H0(t){try{let e=JSON.parse((0,Yt.readFileSync)(lb(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 X0(t){let e=ri(),r=0;for(let n of(()=>{try{return(0,Yt.readdirSync)(e)}catch{return[]}})())if(n.endsWith(".json"))try{JSON.parse((0,Yt.readFileSync)((0,Oa.join)(e,n),"utf8")).payload?.contentSessionId===t&&r++}catch{}return r}function K0(){try{return(0,Yt.readdirSync)(ri()).filter(t=>t.endsWith(".json")).length}catch{return 0}}async function G0(){try{let t=await Aa("/api/processing-status");return(typeof t.queueDepth=="number"?t.queueDepth:0)+K0()}catch{return null}}function db(t=()=>{}){return{async sendPrompt(e){await Zo(e)},async sendToolUse(e){await Iy.execute(e)},async sendSummary(e){await Xy.execute(e)},readRecorded:j0,readLedger:H0,pendingSpoolFor:X0,saveLedger:(e,r)=>$(lb(e),r),usesServerRuntime:()=>Ge().runtime==="server",now:()=>Date.now(),backlog:G0,ensureWorker:()=>Ln(),sleep:e=>new Promise(r=>setTimeout(r,e)),log:t,projectOf:e=>Ao(e).primary,shouldTrack:ct,isDropped(e){let r=z();return sn(e.toolName)||Ft(e.toolName,r.MEMINDEX_SKIP_TOOLS)||Wr(e.agentId,e.agentType,r).skip}}}var Yt,Oa,b0,Dd,w0,Ma,T0,I0,v0,ab,A0,M0,N0,D0,U0,pb=E(()=>{"use strict";Yt=require("fs"),Oa=require("path");wy();Eu();vy();Ky();bu();oe();N();Gy();Fr();st();Wn();Ea();N();ii();Dr();xt();lt();Vy();nr();ib();b0="claude-code",Dd=40,w0=3e3,Ma=15*6e4,T0=5,I0=2e3,v0=15e3,ab=100;A0="Usage: memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]";M0=16e3;N0=20;D0=500;U0=11e3});cn();var mb=require("fs");N();Ie();var er=require("fs"),bf=require("os"),Vs=require("path");oe();N();var Ir=B.transcriptsConfig(),Ys=B.transcriptsState(),cw={version:1,schemas:{},watches:[],stateFile:Ys};function wf(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let n=ue(t.path).replace(/\\/g,"/"),s=(0,Vs.join)((0,bf.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function Tf(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&&wf(t)}var uw={path:"payload.source.subagent.thread_spawn"};function If(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)wf(i)?r?(n+=1,o.push({...i,subagentOnly:!0,subagentSource:{...uw}})):s+=1:o.push(i);return{config:{...t,watches:o},scoped:n,removed:s}}function ue(t){return t&&Jd(t)}var We=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),yf={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 L(t,e,r){if(!t)throw new Error(`${e} ${r}`)}function hn(t,e){L(t===void 0||typeof t=="string",e,"must be a string")}function zs(t,e){L(typeof t=="string"&&t.trim().length>0,e,"must be a non-empty string")}function vf(t,e){L(t===void 0||typeof t=="boolean",e,"must be true or false")}function Rf(t,e){typeof t!="string"&&(L(We(t),e,"must be a path string or an object"),hn(t.path,`${e}.path`),t.coalesce!==void 0&&(L(Array.isArray(t.coalesce),`${e}.coalesce`,"must be an array"),t.coalesce.forEach((r,n)=>Rf(r,`${e}.coalesce[${n}]`))))}function Af(t,e){L(We(t),e,"must be an object");for(let r of["path","regex","contains","not_contains","starts_with","not_starts_with"])hn(t[r],`${e}.${r}`);if(typeof t.regex=="string")try{new RegExp(t.regex)}catch{L(!1,`${e}.regex`,"must be a valid regular expression")}vf(t.exists,`${e}.exists`);for(let r of["in","not_in"])L(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&&(L(Array.isArray(n),`${e}.${r}`,"must be an array"),n.forEach((s,o)=>Af(s,`${e}.${r}[${o}]`)))}}function Va(t,e){L(We(t),e,"must be an object"),zs(t.name,`${e}.name`);for(let r of["eventTypePath","sessionIdPath","cwdPath","projectPath"])hn(t[r],`${e}.${r}`);L(Array.isArray(t.events),`${e}.events`,"must be an array"),t.events.forEach((r,n)=>{let s=`${e}.events[${n}]`;if(L(We(r),s,"must be an object"),L(typeof r.name=="string",`${s}.name`,"must be a string"),L(typeof r.action=="string"&&Object.hasOwn(yf,r.action),`${s}.action`,`must be one of ${Object.keys(yf).join(", ")}`),r.match!==void 0&&Af(r.match,`${s}.match`),r.fields!==void 0){L(We(r.fields),`${s}.fields`,"must be an object");for(let[o,i]of Object.entries(r.fields))Rf(i,`${s}.fields.${o}`)}})}function lw(t,e,r){L(We(t),e,"must be an object"),zs(t.name,`${e}.name`),zs(t.path,`${e}.path`);for(let i of["workspace","project","agentId"])hn(t[i],`${e}.${i}`);for(let i of["startAtEnd","subagentOnly"])vf(t[i],`${e}.${i}`);let{subagentSource:n,context:s}=t;if(n!==void 0&&(L(We(n),`${e}.subagentSource`,"must be an object"),L(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(L(We(s),`${e}.context`,"must be an object"),L(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),hn(s.path,`${e}.context.path`),s.updateOn!==void 0&&(L(Array.isArray(s.updateOn),`${e}.context.updateOn`,"must be an array"),s.updateOn.forEach((i,a)=>L(i==="session_start"||i==="session_end",`${e}.context.updateOn[${a}]`,'must be "session_start" or "session_end"')))),typeof t.schema!="string"){L(We(t.schema),`${e}.schema`,"must be a schema name or an inline schema object"),Va(t.schema,`${e}.schema`);return}zs(t.schema,`${e}.schema`);let o=r?.[t.schema];o!==void 0&&Va(o,`schemas.${t.schema}`)}function dw(t){L(We(t),"the top level","must be an object"),L(t.version===1,"version","must be 1");let{stateFile:e,schemas:r,watches:n}=t;if(L(e==null||typeof e=="string","stateFile","must be a string"),r!==void 0){L(We(r),"schemas","must be an object");for(let[s,o]of Object.entries(r))Va(o,`schemas.${s}`)}L(Array.isArray(n),"watches","must be an array"),n.forEach((s,o)=>lw(s,`watches[${o}]`,r))}function Ya(t=Ir){let e=ue(t);if(!(0,er.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=ht(e);try{dw(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=Ys),r}function qa(t=Ir){let e=ue(t),r=(0,Vs.dirname)(e);(0,er.existsSync)(r)||(0,er.mkdirSync)(r,{recursive:!0}),(0,er.writeFileSync)(e,JSON.stringify(cw,null,2))}var my=require("crypto"),G=require("fs"),hy=require("fs/promises"),Q=require("path");M();var _n=require("fs"),Of=require("path");M();oe();function nt(t,e){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(r=>e(r[1])))}function Pf(t){try{if(!(0,_n.existsSync)(t))return{offsets:{}};let e=ht(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:nt(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(nt(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=o(nt(e.partialBytes,i=>typeof i=="string"&&i.length>0&&Buffer.from(i,"base64").toString("base64")===i))),e.frameLines!==void 0&&(s.frameLines=o(nt(e.frameLines,r))),e.fileIdentities!==void 0&&(s.fileIdentities=o(nt(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=o(nt(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(nt(e.pendingTools,i))).map(([c,u])=>[c,Object.fromEntries(Object.entries(nt(u,i)).map(([l,d])=>[l,nt(d,a)]))]))}return e.cwds!==void 0&&(s.cwds=nt(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 fw=64*1024,Mf=new WeakMap;function pw(t){let e=Mf.get(t);return e||(e=(t.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(t.toolInput)??""))<=fw?t:{toolName:t.toolName},Mf.set(t,e)),e}function gw(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]=pw(a)}}return e}function vr(t,e){try{let r=(0,Of.dirname)(t);(0,_n.existsSync)(r)||(0,_n.mkdirSync)(r,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:gw(e.pendingTools)}:e;$(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 Os=_e(require("path"),1);Eu();$r();M();rt();ut();Dr();Fr();cr();$n();st();Iu();Wn();var vu="write_file",Km={async execute(t){let{sessionId:e,cwd:r,filePath:n,edits:s}=t,o=Y(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(!ct(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=Ge();if(c.runtime==="server"){if(Ft(vu,z().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:vu,tool_input:i,tool_response:a,cwd:r,platformSource:o},...si(r)};try{return await c.client.recordEvent(u),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),await Lr(c.client,Ve(c)),{continue:!0,suppressOutput:!0}}catch(l){if(yt(l))return ze(l.kind,{status:l.status,message:l.message,route:"/v1/events",held:!0}),Ct({op:"event",request:u},Ve(c)),{continue:!0,suppressOutput:!0};if(Ke(l)&&l.isFallbackEligible())ze(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 qe("file_edit",{contentSessionId:e,platformSource:o,toolName:vu,toolInput:i,toolResponse:a,cwd:r}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};xt();N();M();nr();var Je=require("fs"),oi=require("path");M();M();M();Ie();xt();N();An();var Ru="<memindex-context>",Au="</memindex-context>",PR=["agent-mem-context"].map(t=>({open:`<${t}>`,close:`</${t}>`}));function Gm(t){return[{open:Ru,close:Au},...PR].reduce((e,r)=>e??kR(t,r.open,r.close),null)}function kR(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 tU=B.settings();function zm(t,e){let r=`${Ru}
32
+ `).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:By(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||(By(p.timestamp)??Date.now()),transcriptByteOffset:_.transcriptByteOffset,lastUserMessage:_.lastUserMessage},userTurnLine:_.userTurnLine})}}}}return a.filter(u=>!e.currentTurnOnly||u.userTurnLine===o).map(u=>u.call)}var et,e0,Hy=E(()=>{"use strict";et=require("fs");lt();e0=2*1024*1024});function o0(t,e,r,n){if(!e||z().MEMINDEX_CAPTURE_ADVISOR_CALLS!=="true"||Ge().runtime==="server")return;let s=Wy(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+=jy)qe("advisor_calls",{contentSessionId:t,platformSource:n,cwd:r,transcriptPath:e,calls:s.slice(o,o+jy).map(i=>({toolUseId:i.toolUseId,advice:i.advice,advisorModel:i.advisorModel,occurredAtEpoch:i.occurredAtEpoch,lastUserMessage:i.lastUserMessage,transcriptByteOffset:i.transcriptByteOffset}))})}}async function i0(t,e,r){return await hu(t.client,e,void 0,r),f.debug("HOOK","Summary request queued via server"),await Lr(t.client,Ve(t)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}var Xy,Ky,jy,Gy,zy=E(()=>{"use strict";$r();M();Ny();Xy=require("crypto"),Ky=require("path");Fy();lt();rt();xt();ut();Dr();$y();Fr();cr();Un();Hy();st();jy=50;Gy={async execute(t){if(t.cwd&&!ct(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"&&Uy(e);try{o0(e,r,t.cwd,Y(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=we(t.lastAssistantMessage);try{if(r&&t.platform==="claude-code"&&!o){let d=Rd(r,!0,i);s=d.model,o=d.turnId}else s=r?ky(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=Rd(r,!0,i);n=we(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=Y(t.platform),c=t.platform==="claude-code"?Dy():void 0,u=Ge();if(u.runtime==="server"){let d={projectId:u.projectId,contentSessionId:e,platformSource:a,lastAssistantMessage:n,occurredAtEpoch:Date.now()},p=d;try{return await i0(u,d,g=>{p=g})}catch(g){if(yt(g))return ze(g.kind,{status:g.status,message:g.message,route:"/v1/sessions/end",held:!0}),Ct({op:"summarize",request:p},Ve(u)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(Ke(g)&&g.isFallbackEligible())ze(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,Xy.randomUUID)());let l=qe("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 be("/api/spool/nudge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({waitForSummary:!0,contentSessionId:e,platformSource:a,captureKey:(0,Ky.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 Vy=E(()=>{"use strict"});function Yy(t){let e=we(t).trim();return e.length<=Od?e:(f.debug("DB","Truncated stored prompt text to the configured cap",{originalLength:e.length,storedLength:Od}),`${e.slice(0,Od-1)}\u2026`)}var Od,Pd,qy=E(()=>{"use strict";lt();M();Od=4e3,Pd="[media prompt]"});function a0(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function tb(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>vt(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
33
+ `):""}function l0(t){if(t.type!=="user"||t.isSidechain===!0||t.isMeta===!0||t.isCompactSummary===!0)return null;let e=vt(t.message)?t.message:null;if(!e)return null;let r=e.content;if(Array.isArray(r)&&r.some(i=>vt(i)&&i.type==="tool_result"))return null;let n=vt(t.origin)?t.origin:null;if(n){if(n.kind!=="human")return null}else if(typeof t.promptSource=="string"&&!u0.has(t.promptSource))return null;let s=tb(r),o=s.trimStart();return!n&&c0.some(i=>o.startsWith(i))||!s.trim()&&!Array.isArray(r)?null:s}function d0(t){return typeof t=="string"?t:tb(t)}async function*f0(t){let e=(0,eb.createInterface)({input:(0,tt.createReadStream)(t,{encoding:"utf8"}),crlfDelay:1/0});for await(let r of e)if(r.trim())try{let n=JSON.parse(r);vt(n)&&(yield n)}catch{}}async function Jy(t,e={}){let r=[],n=new Map,s=null,o=e.agentId!==void 0,i=0;for await(let a of f0(t)){i++,s===null&&typeof a.cwd=="string"&&a.cwd.trim()&&(s=a.cwd);let c=a0(a.timestamp),u=vt(a.message)?a.message:null;if(a.type==="assistant"&&u&&Array.isArray(u.content)){for(let l of u.content)vt(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(!vt(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=d0(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=l0(a);if(l!==null){let d=typeof a.uuid=="string"&&a.uuid?a.uuid:`${(0,Vt.basename)(t)}:${i}`;r.push({kind:"prompt",timestampMs:c,uuid:d,text:l})}}}}return{events:r,firstCwd:s}}function p0(t){try{let e=JSON.parse((0,tt.readFileSync)(t,"utf8"));return vt(e)&&typeof e.agentType=="string"&&e.agentType?e.agentType:void 0}catch{return}}async function rb(t,e){let r=await Jy(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,Vt.basename)(a,".jsonl").replace(/^agent-/,""),u=p0(a.replace(/\.jsonl$/,".meta.json"));(await Jy(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 Zy(t){try{return(0,tt.statSync)(t).mtimeMs}catch{return 0}}function kd(t){try{return(0,tt.readdirSync)(t)}catch{return[]}}function Qy(t){let e=[];for(let r of kd(t).sort()){let n=g0.exec(r);if(!n)continue;let s=n[1],o=(0,Vt.join)(t,r),i=(0,Vt.join)(t,s,"subagents"),a=(0,tt.existsSync)(i)?kd(i).filter(u=>u.startsWith("agent-")&&u.endsWith(".jsonl")).sort().map(u=>(0,Vt.join)(i,u)):[],c=Math.max(Zy(o),...a.map(Zy));e.push({sessionId:s,transcriptPath:o,subagentPaths:a,lastModifiedMs:c})}return e}function nb(t){let e=Qy(t);return e.length>0?e:kd(t).sort().map(r=>(0,Vt.join)(t,r)).filter(r=>{try{return(0,tt.statSync)(r).isDirectory()}catch{return!1}}).flatMap(Qy)}var tt,Vt,eb,vt,c0,u0,g0,sb=E(()=>{"use strict";tt=require("fs"),Vt=require("path"),eb=require("readline"),vt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);c0=["<command-name>","<command-message>","<local-command-stdout>","<local-command-stderr>","<local-command-caveat>"],u0=new Set(["typed","queued","sdk"]);g0=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i});var xd=E(()=>{"use strict"});var ob=E(()=>{"use strict";xd()});var ib=E(()=>{"use strict";xd()});var ab,Nd,cb=E(()=>{"use strict";N();ab=require("path");sb();ob();ib();Nd={id:"claude-code",label:"Claude Code",platform:"claude-code",defaultDir:()=>(0,ab.join)(Be,"projects"),find:nb,read:rb}});var gb={};Ls(gb,{BACKLOG_HIGH_WATER:()=>Dd,CLAUDE_CODE_PLATFORM:()=>b0,TRANSCRIPT_IMPORT_USAGE:()=>A0,defaultTranscriptImportDeps:()=>pb,formatTranscriptImportResult:()=>W0,isPromptSkippedByWorker:()=>Fd,isoOf:()=>Ds,matchRecordedPrompts:()=>db,parseTranscriptImportArgs:()=>R0,promptKey:()=>an,runTranscriptImport:()=>B0});function R0(t){let e=null,r=null,n=(0,Oa.join)(Be,"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 yr(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 an(t){return Yy(we(t.trim()?t:Pd))}function lb(t){let e=t.replace(/\s+/g," ").trim();return e.length>ub?`${e.slice(0,ub-1)}\u2026`:e}function Ds(t){return t===null?"(no time)":new Date(t).toISOString()}function db(t,e,r){let n=e.map(c=>an(c.text)),s=new Set,o=new Map;for(let c of[...t].reverse()){if(!r.has(c.uuid))continue;let u=an(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=an(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 Cd(t,e){let r=Ty.normalizeInput(t);return r.platform=e,r}function O0(t){let e=r=>Math.min(M0,(typeof r=="string"?r:JSON.stringify(r??"")).length);return e(t.toolInput)+e(t.failed?t.error:t.toolResponse)}function P0(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 k0(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 x0(t){let e=await t.backlog();if(e===null||e<=Dd)return;let r=Date.now(),n=e,s=0;for(;e!==null&&e>Dd;)if(Date.now()-s>=3e4&&(t.log(` waiting for the worker to catch up (${e} items queued)`),s=Date.now()),await t.sleep(w0),e=await t.backlog(),e!==n)n=e??n,r=Date.now();else if(Date.now()-r>Ma)throw new Error(`the worker has not taken any queued work for ${Math.round(Ma/6e4)} minutes (${e} items queued)`)}function C0(t){let e=0;return{async check(r=!1){e++,!(!r&&e<N0)&&(e=0,await x0(t))}}}async function F0(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(D0),r=t.pendingSpoolFor(e),r!==s)s=r,n=t.now();else if(t.now()-n>Ma)throw new Error(`the worker has not taken this session's queued events for ${Math.round(Ma/6e4)} minutes (${r} waiting)`)}function Fd(t){return Vo(t)||t.trim()!==""&&we(t).trim()===""}async function L0(t,e){for(let r=1;;r++)try{await t.sendPrompt(e);return}catch(n){if(!(n instanceof Ur)||r>=T0)throw n;await t.sleep(I0*r)}}async function $0(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=db(t.events.filter(I=>I.kind==="prompt"),r.prompts,u),p=t.events.flatMap((I,y)=>I.kind==="prompt"&&d.has(I.uuid)&&!u.has(I.uuid)?[y]:[]),g=r.hasObservations&&r.prompts.length>0&&r.toolUseIds.size===0,m=t.sessionId,h=new Map;for(let I of r.prompts){let y=an(I.text);h.set(y,Math.max(h.get(y)??Number.NEGATIVE_INFINITY,I.createdAtEpochMs))}let _=null,S=0,b=()=>{s.dryRun||(n.prompts=[...u],n.summaries=[...l],o.saveLedger(m,n))},w=()=>{let I=_?.anchor;if(!I)return;let y=I.atEpochMs+1+_.anchored;return y>=I.beforeEpochMs?Math.max(I.atEpochMs,I.beforeEpochMs-1):(_.anchored++,y)},v=async()=>{if(!_?.summaryOwed||!_.last||!yr(_.last.timestampMs,s))return;let I=_.last.text.join(`
34
+ `);if(s.dryRun)o.log(` summary ${Ds(_.last.timestampMs)} ${lb(I)}`);else{let y=Cd({session_id:m,cwd:e,hook_event_name:"Stop",last_assistant_message:I},a);y.lastAssistantMessage=I,y.spoolAtEpochMs=w(),y.turnId=_.uuid,await i.check(),await o.sendSummary(y),S++,l.add(_.uuid),b()}c.summaries++,c.summaryChars+=I.length};for(let I=0;I<t.events.length;I++){let y=t.events[I];if(y.kind==="prompt"){await v();let R=an(y.text),A=d.get(y.uuid)??null,T=u.has(y.uuid),P=A?r.prompts.find(Ue=>Ue.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){yr(y.timestampMs,s)&&c.alreadyRecorded++;continue}if(T&&Fd(y.text)){_.skippedByWorker=!0,_.summaryOwed=!1,yr(y.timestampMs,s)&&c.alreadyRecorded++;continue}if(_.summaryOwed=!1,!yr(y.timestampMs,s))continue;if(s.dryRun)o.log(` prompt ${Ds(y.timestampMs)} ${lb(y.text)||Pd}`);else{await i.check(!0);let Ue=(h.get(R)??Number.NEGATIVE_INFINITY)+U0-o.now();Ue>0&&await o.sleep(Ue),S>0&&await F0(o,m),S=0,u.add(y.uuid),b(),await L0(o,Cd({session_id:m,cwd:e,hook_event_name:"UserPromptSubmit",prompt:y.text,transcript_path:t.transcriptPath},a)),h.set(R,o.now())}if(Fd(y.text)){_.skippedByWorker=!0,c.prompts++;continue}p.some(Ue=>Ue>I)&&(c.outOfOrder++,o.log(` note: the prompt at ${Ds(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(yr(y.timestampMs,s)&&!_?.skippedByWorker){if(r.toolUseIds.has(y.toolUseId)||g&&(!_||_.capturedLive)){c.alreadyRecorded++;continue}if(!o.isDropped(y)){if(s.dryRun){let R=y.agentId?` (subagent ${y.agentType??y.agentId})`:"";o.log(` tool use ${Ds(y.timestampMs)} ${y.toolName} ${y.toolUseId}${y.failed?" failed":""}${R}`)}else{let R=Cd(P0(m,e,y),a);R.spoolAtEpochMs=w(),await o.sendToolUse(R),S++,r.toolUseIds.add(y.toolUseId),await i.check()}c.toolUses++,c.toolChars+=O0(y)}}}return await v(),c}async function B0(t,e=pb(),r=Nd){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,Yt.existsSync)(t.projectDir))return n.error=`no ${r===Nd?"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=C0(e);for(let a of s){n.sessionsScanned++;let c;try{c=await r.read(a,g=>yr(g,t))}catch(g){e.log(`Skipped ${a.transcriptPath}: ${g instanceof Error?g.message:String(g)}`);continue}if(!c.events.some(g=>yr(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 k0(u,()=>$0(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 W0(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 Aa(t){let e=await be(t,{timeoutMs:v0});if(!e.ok)throw new Error(`${t} answered ${e.status}`);return e.json()}async function H0(t){let e=encodeURIComponent(t);try{let r=[];for(let o=0;;o+=100){let i=await Aa(`/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 Aa(`/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 Aa(`/api/observations?contentSessionId=${e}&limit=1`);return{prompts:r,toolUseIds:n,hasObservations:(s.items?.length??0)>0}}catch{return null}}function fb(t){return(0,Oa.join)(x(),"state","transcript-import",`${t.replace(/[^A-Za-z0-9_-]/g,"_")}.json`)}function j0(t){try{let e=JSON.parse((0,Yt.readFileSync)(fb(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 X0(t){let e=ri(),r=0;for(let n of(()=>{try{return(0,Yt.readdirSync)(e)}catch{return[]}})())if(n.endsWith(".json"))try{JSON.parse((0,Yt.readFileSync)((0,Oa.join)(e,n),"utf8")).payload?.contentSessionId===t&&r++}catch{}return r}function K0(){try{return(0,Yt.readdirSync)(ri()).filter(t=>t.endsWith(".json")).length}catch{return 0}}async function G0(){try{let t=await Aa("/api/processing-status");return(typeof t.queueDepth=="number"?t.queueDepth:0)+K0()}catch{return null}}function pb(t=()=>{}){return{async sendPrompt(e){await Zo(e)},async sendToolUse(e){await Ry.execute(e)},async sendSummary(e){await Gy.execute(e)},readRecorded:H0,readLedger:j0,pendingSpoolFor:X0,saveLedger:(e,r)=>$(fb(e),r),usesServerRuntime:()=>Ge().runtime==="server",now:()=>Date.now(),backlog:G0,ensureWorker:()=>Fn(),sleep:e=>new Promise(r=>setTimeout(r,e)),log:t,projectOf:e=>Ao(e).primary,shouldTrack:ct,isDropped(e){let r=z();return sn(e.toolName)||Ft(e.toolName,r.MEMINDEX_SKIP_TOOLS)||Wr(e.agentId,e.agentType,r).skip}}}var Yt,Oa,b0,Dd,w0,Ma,T0,I0,v0,ub,A0,M0,N0,D0,U0,mb=E(()=>{"use strict";Yt=require("fs"),Oa=require("path");Iy();Eu();Ay();zy();bu();oe();N();Vy();Fr();st();Bn();Ea();N();ii();Dr();xt();lt();qy();nr();cb();b0="claude-code",Dd=40,w0=3e3,Ma=15*6e4,T0=5,I0=2e3,v0=15e3,ub=100;A0="Usage: memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]";M0=16e3;N0=20;D0=500;U0=11e3});cn();var _b=require("fs");N();Ie();var er=require("fs"),Tf=require("os"),Vs=require("path");oe();N();var Ir=B.transcriptsConfig(),Ys=B.transcriptsState(),cw={version:1,schemas:{},watches:[],stateFile:Ys};function If(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let n=ue(t.path).replace(/\\/g,"/"),s=(0,Vs.join)((0,Tf.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function vf(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&&If(t)}var uw={path:"payload.source.subagent.thread_spawn"};function Rf(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)If(i)?r?(n+=1,o.push({...i,subagentOnly:!0,subagentSource:{...uw}})):s+=1:o.push(i);return{config:{...t,watches:o},scoped:n,removed:s}}function ue(t){return t&&Jd(t)}var We=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),wf={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 L(t,e,r){if(!t)throw new Error(`${e} ${r}`)}function mn(t,e){L(t===void 0||typeof t=="string",e,"must be a string")}function zs(t,e){L(typeof t=="string"&&t.trim().length>0,e,"must be a non-empty string")}function Af(t,e){L(t===void 0||typeof t=="boolean",e,"must be true or false")}function Mf(t,e){typeof t!="string"&&(L(We(t),e,"must be a path string or an object"),mn(t.path,`${e}.path`),t.coalesce!==void 0&&(L(Array.isArray(t.coalesce),`${e}.coalesce`,"must be an array"),t.coalesce.forEach((r,n)=>Mf(r,`${e}.coalesce[${n}]`))))}function Of(t,e){L(We(t),e,"must be an object");for(let r of["path","regex","contains","not_contains","starts_with","not_starts_with"])mn(t[r],`${e}.${r}`);if(typeof t.regex=="string")try{new RegExp(t.regex)}catch{L(!1,`${e}.regex`,"must be a valid regular expression")}Af(t.exists,`${e}.exists`);for(let r of["in","not_in"])L(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&&(L(Array.isArray(n),`${e}.${r}`,"must be an array"),n.forEach((s,o)=>Of(s,`${e}.${r}[${o}]`)))}}function Va(t,e){L(We(t),e,"must be an object"),zs(t.name,`${e}.name`);for(let r of["eventTypePath","sessionIdPath","cwdPath","projectPath"])mn(t[r],`${e}.${r}`);L(Array.isArray(t.events),`${e}.events`,"must be an array"),t.events.forEach((r,n)=>{let s=`${e}.events[${n}]`;if(L(We(r),s,"must be an object"),L(typeof r.name=="string",`${s}.name`,"must be a string"),L(typeof r.action=="string"&&Object.hasOwn(wf,r.action),`${s}.action`,`must be one of ${Object.keys(wf).join(", ")}`),r.match!==void 0&&Of(r.match,`${s}.match`),r.fields!==void 0){L(We(r.fields),`${s}.fields`,"must be an object");for(let[o,i]of Object.entries(r.fields))Mf(i,`${s}.fields.${o}`)}})}function lw(t,e,r){L(We(t),e,"must be an object"),zs(t.name,`${e}.name`),zs(t.path,`${e}.path`);for(let i of["workspace","project","agentId"])mn(t[i],`${e}.${i}`);for(let i of["startAtEnd","subagentOnly"])Af(t[i],`${e}.${i}`);let{subagentSource:n,context:s}=t;if(n!==void 0&&(L(We(n),`${e}.subagentSource`,"must be an object"),L(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(L(We(s),`${e}.context`,"must be an object"),L(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),mn(s.path,`${e}.context.path`),s.updateOn!==void 0&&(L(Array.isArray(s.updateOn),`${e}.context.updateOn`,"must be an array"),s.updateOn.forEach((i,a)=>L(i==="session_start"||i==="session_end",`${e}.context.updateOn[${a}]`,'must be "session_start" or "session_end"')))),typeof t.schema!="string"){L(We(t.schema),`${e}.schema`,"must be a schema name or an inline schema object"),Va(t.schema,`${e}.schema`);return}zs(t.schema,`${e}.schema`);let o=r?.[t.schema];o!==void 0&&Va(o,`schemas.${t.schema}`)}function dw(t){L(We(t),"the top level","must be an object"),L(t.version===1,"version","must be 1");let{stateFile:e,schemas:r,watches:n}=t;if(L(e==null||typeof e=="string","stateFile","must be a string"),r!==void 0){L(We(r),"schemas","must be an object");for(let[s,o]of Object.entries(r))Va(o,`schemas.${s}`)}L(Array.isArray(n),"watches","must be an array"),n.forEach((s,o)=>lw(s,`watches[${o}]`,r))}function Ya(t=Ir){let e=ue(t);if(!(0,er.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=ht(e);try{dw(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=Ys),r}function qa(t=Ir){let e=ue(t),r=(0,Vs.dirname)(e);(0,er.existsSync)(r)||(0,er.mkdirSync)(r,{recursive:!0}),(0,er.writeFileSync)(e,JSON.stringify(cw,null,2))}var _y=require("crypto"),G=require("fs"),Ey=require("fs/promises"),Q=require("path");M();var hn=require("fs"),kf=require("path");M();oe();function nt(t,e){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(r=>e(r[1])))}function xf(t){try{if(!(0,hn.existsSync)(t))return{offsets:{}};let e=ht(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:nt(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(nt(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=o(nt(e.partialBytes,i=>typeof i=="string"&&i.length>0&&Buffer.from(i,"base64").toString("base64")===i))),e.frameLines!==void 0&&(s.frameLines=o(nt(e.frameLines,r))),e.fileIdentities!==void 0&&(s.fileIdentities=o(nt(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=o(nt(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(nt(e.pendingTools,i))).map(([c,u])=>[c,Object.fromEntries(Object.entries(nt(u,i)).map(([l,d])=>[l,nt(d,a)]))]))}return e.cwds!==void 0&&(s.cwds=nt(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 fw=64*1024,Pf=new WeakMap;function pw(t){let e=Pf.get(t);return e||(e=(t.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(t.toolInput)??""))<=fw?t:{toolName:t.toolName},Pf.set(t,e)),e}function gw(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]=pw(a)}}return e}function vr(t,e){try{let r=(0,kf.dirname)(t);(0,hn.existsSync)(r)||(0,hn.mkdirSync)(r,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:gw(e.pendingTools)}:e;$(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 Ms=_e(require("path"),1);Eu();$r();M();rt();ut();Dr();Fr();cr();Un();st();Iu();Bn();var vu="write_file",zm={async execute(t){let{sessionId:e,cwd:r,filePath:n,edits:s}=t,o=Y(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(!ct(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=Ge();if(c.runtime==="server"){if(Ft(vu,z().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:vu,tool_input:i,tool_response:a,cwd:r,platformSource:o},...si(r)};try{return await c.client.recordEvent(u),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),await Lr(c.client,Ve(c)),{continue:!0,suppressOutput:!0}}catch(l){if(yt(l))return ze(l.kind,{status:l.status,message:l.message,route:"/v1/events",held:!0}),Ct({op:"event",request:u},Ve(c)),{continue:!0,suppressOutput:!0};if(Ke(l)&&l.isFallbackEligible())ze(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 qe("file_edit",{contentSessionId:e,platformSource:o,toolName:vu,toolInput:i,toolResponse:a,cwd:r}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};xt();N();M();nr();var Je=require("fs"),oi=require("path");M();M();M();Ie();xt();N();Rn();var Ru="<memindex-context>",Au="</memindex-context>",PR=["agent-mem-context"].map(t=>({open:`<${t}>`,close:`</${t}>`}));function Vm(t){return[{open:Ru,close:Au},...PR].reduce((e,r)=>e??kR(t,r.open,r.close),null)}function kR(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 tU=B.settings();function Ym(t,e){let r=`${Ru}
35
35
  ${e}
36
- ${Au}`;if(!t)return r;let n=Gm(t);return n?t.substring(0,n.start)+r+t.substring(n.end):t+`
36
+ ${Au}`;if(!t)return r;let n=Vm(t);return n?t.substring(0,n.start)+r+t.substring(n.end):t+`
37
37
 
38
- ${r}`}M();function Vm(t,e){if(!t)return;let r=(0,oi.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=(0,oi.dirname)(t);(0,Je.existsSync)(n)||(0,Je.mkdirSync)(n,{recursive:!0});let s="";(0,Je.existsSync)(t)&&(s=(0,Je.readFileSync)(t,"utf-8"));let o=`# Memory Context
38
+ ${r}`}M();function qm(t,e){if(!t)return;let r=(0,oi.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=(0,oi.dirname)(t);(0,Je.existsSync)(n)||(0,Je.mkdirSync)(n,{recursive:!0});let s="";(0,Je.existsSync)(t)&&(s=(0,Je.readFileSync)(t,"utf-8"));let o=`# Memory Context
39
39
 
40
- ${e}`,i=zm(s,o),a=`${t}.tmp`;try{(0,Je.writeFileSync)(a,i),(0,Je.renameSync)(a,t)}catch(c){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},c instanceof Error?c:new Error(String(c)))}}M();function xR(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 jn(t,e){if(!e)return;let r=xR(e),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}function Ym(t){return t==null||t===""}function qm(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 Br(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=qm(t,r);return n!==void 0?n:jn(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let n of t.coalesce){let s=Br(n,e,r);if(!Ym(s))return s}if(t.path){let n=qm(t.path,r);if(n!==void 0)return n;let s=jn(e,t.path);if(!Ym(s))return s}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function Jm(t,e,r){let n={};if(!t)return n;for(let[s,o]of Object.entries(t))n[s]=Br(o,e,r);return n}function Hn(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(!Hn(t,i,r))return!1}if(e.any!==void 0&&(!Array.isArray(e.any)||!e.any.some(i=>Hn(t,i,r))))return!1;let n=e.path||r.eventTypePath||"type",s=n?jn(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}ut();$r();M();lt();An();ii();Wn();Ie();N();var ur=require("path");N();function CR(t=B.dataDir()){return(0,ur.join)(t,"bottles")}function th(t,e){let r=(0,ur.resolve)(CR(e));return(0,ur.resolve)(t).startsWith(r+ur.sep)}nr();ut();M();var Xn=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 jr=require("path");function nh(){let t=DR();return async e=>{for(let r of e)r.module=t(r.filename);return e}}function DR(t=process.argv[1]?(0,jr.dirname)(process.argv[1]):process.cwd(),e=jr.sep==="\\"){let r=e?rh(t):t;return n=>{if(!n)return;let s=e?rh(n):n,{dir:o,base:i,ext:a}=jr.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 rh(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var ee={};Us(ee,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>wi,DOMExceptionCoercer:()=>Ku,EXCEPTION_STEP_INTERNAL_FIELDS:()=>es,ErrorCoercer:()=>qn,ErrorEventCoercer:()=>Gu,ErrorPropertiesBuilder:()=>Yn,EventCoercer:()=>zu,ExceptionStepsBuffer:()=>Ju,ObjectCoercer:()=>Zn,PrimitiveCoercer:()=>Qn,PromiseRejectionEventCoercer:()=>Vu,ReduceableCache:()=>Yu,StringCoercer:()=>Jn,chromeStackLineParser:()=>Wu,createDefaultStackParser:()=>Xu,createStackParser:()=>zh,geckoStackLineParser:()=>ju,getInjectedReleaseId:()=>YA,getUtf8ByteLength:()=>Yh,nodeStackLineParser:()=>Wh,opera10StackLineParser:()=>Uh,opera11StackLineParser:()=>$h,resolveExceptionStepsConfig:()=>qu,reverseAndStripFrames:()=>Gh,stripReservedExceptionStepFields:()=>GA,winjsStackLineParser:()=>Lh});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 Lt(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 FR=Array.isArray,oh=Object.prototype,wU=oh.hasOwnProperty,ai=oh.toString,Te=FR||function(t){return ai.call(t)==="[object Array]"};var Kn=t=>t===Object(t)&&!Te(t);var bt=t=>t===void 0,ce=t=>ai.call(t)=="[object String]",Mu=t=>ce(t)&&t.trim().length===0,Ou=t=>t===null,Ze=t=>bt(t)||Ou(t),Hr=t=>ai.call(t)=="[object Number]"&&t===t;var ih=t=>ai.call(t)==="[object Boolean]";function ci(t){return t===null||typeof t!="object"}function lr(t,e){return Object.prototype.toString.call(t)===`[object ${e}]`}function Ut(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 uh(t,Error)}}function ah(t){return lr(t,"ErrorEvent")}function Xr(t){return"u">typeof Event&&uh(t,Event)}function ch(t){return lr(t,"Object")}function uh(t,e){try{return t instanceof e}catch{return!1}}var LR=["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"],ui=new Map,UR=256;function $R(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 lh=function(t,e=[]){if(!t)return!1;let r=$R(t,e),n=ui.get(r);if(n!==void 0)return n;let s=t.toLowerCase(),o=LR.concat(e).some(i=>s.indexOf(i.toLowerCase())!==-1);return ui.size>=UR&&ui.clear(),ui.set(r,o),o};function Gn(t,e,r,n,s){return e>r&&(n.warn("min cannot be greater than max."),e=r),Hr(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),Gn(s??r,e,r,n))}var BR=864e5,WR=1,jR=10;function dh(t={}){return{refillRate:t.exceptionRateLimiterRefillRate??t.__exceptionRateLimiterRefillRate??WR,bucketSize:t.exceptionRateLimiterBucketSize??t.__exceptionRateLimiterBucketSize??jR}}var li=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Gn(e.bucketSize,0,100,e._logger),this._refillRate=Gn(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Gn(e.refillInterval,0,BR,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 di="0123456789abcdef",fi=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+=di.charAt(this.bytes[r]>>>4),e+=di.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+=di.charAt(this.bytes[r]>>>4),e+=di.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??HR()}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 fi.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,fi.ofInner(e)}},HR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),fh,fe=()=>XR().toString(),XR=()=>(fh||(fh=new Pu)).generate();var pi=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 KR(t=console){return{log:t.log.bind(t),warn:t.warn.bind(t),error:t.error.bind(t),debug:t.debug.bind(t)}}var ph=(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=>ph(`${t} ${o}`,e,r)}},GR=t=>t();function gh(t,e=GR){return ph(t,e,KR())}var Gr="Mobile",mi="iOS",Kr="Android",Sh="Tablet",LU=Kr+" "+Sh;var VR="Apple",UU=VR+" Watch",yh="Safari",hi="BlackBerry",bh="Samsung",YR=bh+"Browser",qR=bh+" Internet",_i="Chrome",JR=_i+" OS",ZR=_i+" "+mi,wh="Internet Explorer",QR=wh+" "+Gr,Nu="Opera",$U=Nu+" Mini",Th="Edge",eA="Microsoft "+Th,Cu="Firefox",tA=Cu+" "+mi,Du="Nintendo",Fu="PlayStation",gi="Xbox",rA=Kr+" "+Gr,nA=Gr+" "+yh,zn="Windows",sA=zn+" Phone";var Ih="Generic",BU=Ih+" "+Gr.toLowerCase(),WU=Ih+" "+Sh.toLowerCase(),oA="Konqueror",iA="Oculus Browser",mh="Vivaldi",aA="Yandex",hh="Whale",cA="DuckDuckGo",uA="Pale Moon",_h="Waterfox",Eh="Brave",vh="Claude",Rh="Codex",Ah="ChatGPT",lA="Google Search App",X="(\\d+(\\.\\d+)?)",ku=new RegExp("Version/"+X),xu=new RegExp("("+vh+"|"+Rh+"|"+Ah+")\\/"+X);var jU=new RegExp(gi,"i"),HU=new RegExp(Fu+" \\w+","i"),XU=new RegExp(Du+" \\w+","i"),dA=new RegExp(hi+"|PlayBook|BB10","i"),fA={"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 KU={[QR]:[new RegExp("rv:"+X)],[eA]:[new RegExp(Th+"?\\/"+X)],[_i]:[new RegExp("("+_i+"|CrMo)\\/"+X)],[ZR]:[new RegExp("CriOS\\/"+X)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+X)],[yh]:[ku],[nA]:[ku],[Nu]:[new RegExp("("+Nu+"|OPR)\\/"+X)],[Cu]:[new RegExp(Cu+"\\/"+X)],[tA]:[new RegExp("FxiOS\\/"+X)],[oA]:[new RegExp("Konqueror[:/]?"+X,"i")],[hi]:[new RegExp(hi+" "+X),ku],[rA]:[new RegExp("android\\s"+X,"i")],[qR]:[new RegExp(YR+"\\/"+X)],[iA]:[new RegExp("OculusBrowser\\/"+X)],[mh]:[new RegExp(mh+"\\/"+X)],[aA]:[new RegExp("YaBrowser\\/"+X)],[hh]:[new RegExp(hh+"\\/"+X)],[Eh]:[new RegExp(Eh+"\\/"+X)],[vh]:[xu],[Rh]:[xu],[Ah]:[xu],[cA]:[new RegExp("(DuckDuckGo|Ddg)\\/"+X)],[uA]:[new RegExp("PaleMoon\\/"+X)],[_h]:[new RegExp(_h+"\\/"+X)],[lA]:[new RegExp("GSA\\/"+X)],[wh]:[new RegExp("(rv:|MSIE )"+X)],Mozilla:[new RegExp("rv:"+X)]};var GU=[[new RegExp(gi+"; "+gi+" (.*?)[);]","i"),t=>[gi,t&&t[1]||""]],[new RegExp(Du,"i"),[Du,""]],[new RegExp(Fu,"i"),[Fu,""]],[dA,[hi,""]],[new RegExp(zn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[sA,""];if(new RegExp(Gr).test(e)&&!/IEMobile\b/.test(e))return[zn+" "+Gr,""];let r=/Windows NT ([0-9.]+)/i.exec(e);if(r&&r[1]){let n=r[1],s=fA[n]||"";return/arm/i.test(e)&&(s="RT"),[zn,s]}return[zn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){let e=[t[3],t[4],t[5]||"0"];return[mi,e.join(".")]}return[mi,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=bt(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Kr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Kr+")","i"),t=>{if(t&&t[2]){let e=[t[2],t[3],t[4]||"0"];return[Kr,e.join(".")]}return[Kr,""]}],[/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/,[JR,""]],[/Linux|debian/i,["Linux",""]]];var Ei="[Circular]",Si="[Truncated]",ke="[Unserializable]",Mh="[Function]",YU=Date.prototype.getTime,qU=Date.prototype.toISOString;function dt(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 wt(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=ke}Object.defineProperty(t,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return t}function Lu(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 dr=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 Oh="utf8",pA=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gA(t){return typeof t=="string"&&pA.test(t)}function fr(t,e){return gA(t)?t:e()}function zr(t,e){let r=new Error(e);try{Object.defineProperty(r,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Ph(t){return t?.replace(/\/+$/,"")}async function kh(t,e){let r=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await t()}catch(s){if(r=s,!e.retryCheck(s))throw s}}throw r}function Uu(){return new Date().toISOString()}function pe(t,e){let r=setTimeout(t,e);return r?.unref&&r?.unref(),r}async function $t(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 xh=t=>t&&typeof t.then=="function";function Vn(t){return Promise.all(t.map(e=>(e??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var $u,Nh,Ch,Vr;function Fh(t){let e=globalThis._posthogChunkIds,r=globalThis._debugIds;if(!e&&!r)return;let n=e?Object.keys(e):[],s=r?Object.keys(r):[];if(Vr&&Dh(e,n,Nh)&&Dh(r,s,Ch))return Vr;Nh=e?{...e}:void 0,Ch=r?{...r}:void 0,Vr={},$u??={};let o=(i,a)=>{for(let c of i){let u=a[c];if(!u)continue;let l=$u?.[c];if(l){Vr[l]=u;continue}let d=t(c);for(let p=d.length-1;p>=0;p--){let g=d[p]?.filename;if(g){Vr[g]=u,$u[c]=g;break}}}};return r&&o(s,r),e&&o(n,e),Vr}function Dh(t,e,r){return!t||!r?t===r:e.length===Object.keys(r).length&&e.every(n=>t[n]===r[n])}var Bu=50,mA=1e3,hA=100,_A=4,Yn=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&&Te(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:Fh(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(Ut(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&n<hA;n++){let s=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let o=e.errors;return Te(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>_A||h>0&&c.indexOf(g)!==-1)return this.coerceFallback(_);let w=typeof g=="object"&&g!==null||typeof g=="function";if(h===0&&s>=Bu||w&&a.has(g))return;w&&a.add(g),h===0&&s++;let T=this.getAggregateErrors(g);i||=!!T;let R;try{if(R=this.applyCoercers(g,_),!R)throw u}catch(v){if(v===u){h===0&&s--;return}if(!i)throw v;R=this.coerceFallback(_)}if(!T||s>=Bu)return R;let I;try{I=T.length}catch{return R}if(!Number.isInteger(I)||I<0||I>4294967295)return R;let y=[];for(let v=0;s<Bu&&o<mA&&v<I;v++){o++;let A;try{A=_.next(T[v])}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 se="?",EA="<anonymous>",SA=/^([a-z][a-z0-9.+-]+):/i,yA=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function bA(t){if(!t||t===EA)return!1;let e=SA.exec(t);return!e||yA.includes(e[1].toLowerCase())}function ft(t,e,r,n,s){let o={platform:t,filename:e,function:r==="<anonymous>"?se:r,in_app:bA(e)};return bt(n)||(o.lineno=n),bt(s)||(o.colno=s),o}var yi=(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]:se,r?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};var wA=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,TA=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,IA=/\((\S*)(?::(\d+))(?::(\d+))\)/,Wu=(t,e)=>{let r=wA.exec(t);if(r){let[,s,o,i]=r;return ft(e,s,se,+o,+i)}let n=TA.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=IA.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,i]=yi(n[1]||se,n[2]);return ft(e,i,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var vA=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,RA=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ju=(t,e)=>{let r=vA.exec(t);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let i=RA.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]||se;return[o,s]=yi(o,s),ft(e,s,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var AA=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Lh=(t,e)=>{let r=AA.exec(t);return r?ft(e,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var MA=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Uh=(t,e)=>{let r=MA.exec(t);return r?ft(e,r[2],r[3]||se,+r[1]):void 0},OA=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,$h=(t,e)=>{let r=OA.exec(t);return r?ft(e,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var PA=/^\s*[-]{4,}$/,kA=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,xA=/^Promise\.(?:all|any)$/,NA=/^index \d+$/,CA="node:internal/promise",Wh=(t,e)=>{let r=t.match(kA);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||se,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]),xA.test(o)&&NA.test(c||"")&&(c=CA),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:Bh(r[3]),colno:Bh(r[4]),in_app:DA(c||"",u),platform:e}}if(t.match(PA))return{filename:t,platform:e}};function DA(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 Bh(t){return parseInt(t||"",10)||void 0}var jh=/\(error: (.*)\)/,Hh=50,FA=10,LA=1e3;function Hu(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function UA(t){for(let e=1;e<=FA;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(!Hu(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 $A(t,e){let r=e.start+e.length,n=Kh(t,e);n&&t.splice(r+n===t.length?r:e.start,n)}function Xh(t,e){let r=e.start;for(;r>0&&Hu(t[r-1],t[r-1+e.length]);)r--;return e.start-r}function Kh(t,e){let r=e.start+e.length,n=r;for(;n<t.length&&Hu(t[n],t[n-e.length]);)n++;return n-r}function BA(t,e){let r=e[0],n=t.length-(r?Xh(t,r):0);for(let s of e)n-=Kh(t,s);return n}function WA(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++)jA(e,n,r)&&(r=n);t.push(...t.splice(0,r))}function jA(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 Gh(t){if(!t.length)return[];let e=Array.from(t);return e.reverse(),e.slice(0,Hh).map(r=>({...r,filename:r.filename||HA(e).filename,function:r.function||se}))}function HA(t){return t[t.length-1]||{}}function Xu(){return zh("web:javascript",Wu,ju)}function zh(t,...e){return(r,n=0)=>{let s=[],o=r.split(`
41
- `),i=Math.min(o.length,n+LA),a=[];for(let l=n;l<i;l++){let d=o[l];if(d.length>1024)continue;let p=jh.test(d)?d.replace(jh,"$1"):d;if(!p.match(/\S*Error: /)){for(let g of e){let m=g(p,t);if(m){s.push(m);let h=UA(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(BA(s,a)>=Hh)break}}let c=[...a].sort((l,d)=>d.start-l.start),u=c[c.length-1];if(u){let l=Xh(s,u);s.splice(u.start-l,l);for(let d of c)d.start-=l}for(let l of c)$A(s,l);return a.some(l=>l.start===0&&s.length===l.length)&&WA(s),Gh(s)}}var Ku=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,r){let n=ce(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 lr(e,"DOMException")}isDOMError(e){return lr(e,"DOMError")}};var qn=class{match(e){return Ut(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 Gu=class{match(e){if(!ah(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 ce(e.message)&&e.message.length>0}_buildLocationStack(e){let r=e,n=r.lineno??0,s=r.colno??0;if(!(!ce(r.filename)||r.filename.length===0)&&n!==0)return`Error
42
- at ${r.filename}:${n}:${s}`}};var XA=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Jn=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(XA);return s&&(r=s[1],n=s[2]),[r,n]}};var Vh=["fatal","error","warning","log","info","debug"];function bi(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 Zn=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(Xr(e))return e.constructor.name;let r="name"in e?e.name:void 0;return ce(r)&&!Mu(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=bi(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return ce(e)&&!Mu(e)&&Vh.indexOf(e)>=0}getStack(e){try{return ce(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ce(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(Ut(n))return n}}getObjectClassName(e){try{let r=Object.getPrototypeOf(e);return r?r.constructor.name:void 0}catch{return}}};var zu=class{match(e){return Xr(e)}coerce(e,r){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${bi(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Qn=class{match(e){return ci(e)}coerce(e,r){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Vu=class{match(e){return lr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xr(e))return!1;try{let r=e.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(e,r){let n=this.getUnhandledRejectionReason(e);return ci(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var Yu=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let r=this._cache.get(e);if(r!==void 0)return this._cache.delete(e),this._cache.set(e,r),r}set(e,r){this._cache.set(e,r)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var es={MESSAGE:"$message",TIMESTAMP:"$timestamp"},KA=new Set([es.MESSAGE,es.TIMESTAMP]),wi={enabled:!0,max_bytes:32768};function qu(t){return t?{enabled:t.enabled??wi.enabled,max_bytes:zA(t.max_bytes,wi.max_bytes)}:{...wi}}function GA(t){if(!t)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(t).reduce((n,s)=>KA.has(s)?(e.push(s),n):(n[s]=t[s],n),{}),droppedKeys:e}}var Ju=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=qu(e)}setConfig(e){this._config=qu(e),this._trimToMaxBytes()}add(e){let r=VA(e);if(!r)return;let n=Yh(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 zA(t,e){if(!Hr(t)||t===1/0||t===-1/0)return e;let r=Math.floor(t);return r<0?e:r}function VA(t){let e;try{e=Lt(t)}catch{return}try{let r=JSON.parse(e);if(!Kn(r))return;let n=r,s=n[es.MESSAGE],o=n[es.TIMESTAMP];return!ce(s)||s.trim().length===0||!ce(o)&&!Hr(o)?void 0:{step:n,json:e}}catch{return}}function Yh(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 YA(){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 Zu=t=>{if("flags"in t){let e=qh(t.flags),r=Jh(t.flags);return{...t,featureFlags:e,featureFlagPayloads:r}}{let e=t.featureFlags??{},r=Object.fromEntries(Object.entries(t.featureFlagPayloads||{}).map(([s,o])=>[s,Yr(o)])),n=Object.fromEntries(Object.entries(e).map(([s,o])=>[s,qA(s,o,r[s])]));return{...t,featureFlags:e,featureFlagPayloads:r,flags:n}}};function qA(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 qh=t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,ts(r)]).filter(([,e])=>e!==void 0)),Jh=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?Yr(n):void 0]}))},ts=t=>t===void 0?void 0:t.variant??t.enabled,Yr=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};var Zh=["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"],JA=["$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",...Zh,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],rs=(t,e=[])=>{let r={},n=s=>{t[s]!==void 0&&(r[s]=t[s])};return JA.forEach(n),e.forEach(n),r};var Ti=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 Qu(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var QA="NativeGzipValidationError",eM=31,tM=139,rM=8,nM=t=>t.length>=2&&t[0]===eM&&t[1]===tM;var ns,sM=()=>{if(ns)return ns;ns=[];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;ns[t]=e>>>0}return ns},oM=t=>{let e=sM(),r=4294967295;for(let n=0;n<t.length;n++)r=e[(r^t[n])&255]^r>>>8;return(4294967295^r)>>>0},Ii=t=>{throw zr(QA,`Native gzip produced invalid output: ${t}`)},iM=async(t,e)=>{t.size<18&&Ii("too-short");let r=new Uint8Array(await t.slice(0,10).arrayBuffer());(!nM(r)||r[2]!==rM)&&Ii("invalid-header");let n=new DataView(await t.slice(t.size-8).arrayBuffer());n.getUint32(0,!0)!==oM(e)&&Ii("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&Ii("invalid-size")};async function ss(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 iM(c,n),c}catch(n){if(r?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var xe=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 Lu(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=zr("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=zr("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{}})()}},Tt=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var aM=(t,e)=>{for(let r of Object.keys(e))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(t[r]=e[r])};async function Qh(t){if(t instanceof xe){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 cM(t){return typeof t=="object"&&(t instanceof xe||n_(t))}function n_(t){return t instanceof Tt}function uM(t){if(t instanceof xe)return t.status===502||t.status===504;if(!(t instanceof Tt))return!1;let e=t.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var e_=10485760;function t_(t){try{return typeof t!="string"?t instanceof Uint8Array?t.byteLength:t.size:"u">typeof Buffer?Buffer.byteLength(t,Oh):new TextEncoder().encode(t).length}catch{return 0}}function qr(t){return typeof t=="object"&&t instanceof xe&&t.status===413}function vi(t){return t instanceof xe?t.status===408||t.status===429||t.status>=500:n_(t)}function r_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var el="default",os=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Yn([new qn,new Zn,new Jn,new Qn],Xu())}getEvaluationRuntime(){}constructor(e,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new pi,this._events=new Ti,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=gh("[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=Ph(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:vi},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=!Qu()||(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 aM(n,r),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=rs(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:uM},this.featureFlagsRequestTimeoutMs).then(p=>({success:!0,response:Zu(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(e){if(e instanceof xe)return{type:"api_error",statusCode:e.status};if(e instanceof Tt){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=ts(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 el}persistedQueueKeyForRoute(e){return he.Queue}getActiveQueueRoutes(){return[el]}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=r_(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=fr(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:Uu(),uuid:fr(r?.uuid,fe)};return(r?.disableGeoip??this.disableGeoip)&&(r_(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 Qh(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(()=>Vn([r])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Vn([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 ss(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,r,n=el){let s={api_key:this.apiKey,batch:e.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:Uu()};this.historicalMigration&&(s.historical_migration=!0);let o=Lt(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=>qr(d)?!1:vi(d)};try{await this.sendBatch(c,l,e)}catch(d){if(qr(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 Tt||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=t_(s);if(o>e_)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${o} bytes: the endpoint accepts at most ${e_}`)),{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=>qr(l)||l instanceof xe&&l.retryAfterMs!==void 0?!1:vi(l)}),{kind:"ok"}}catch(l){if(qr(l))return{kind:"too-large"};if(vi(l)){let d=l instanceof xe?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=t_(i),c={...this._retryOptions,...s},u=0;return await kh(async()=>{u++;let l=new AbortController,d=o??this.requestTimeout,p=Date.now()+d,g,m=new Promise((T,R)=>{g=pe(()=>{let I=zr("AbortError",`Request timed out after ${d}ms`);R(I),l.abort(I)},d)}),h,_=!1,S,w=()=>S??=(async()=>{try{await h?.body?.cancel()}catch{}})();try{let T;try{T=this.fetch(e,{signal:l.signal,...r})}catch(y){throw new Tt(y)}T.then(y=>{l.signal.aborted&&!_&&Promise.resolve(y.body?.cancel()).catch(()=>{})}).catch(()=>{});try{h=await Promise.race([T,m]),_=!0}catch(y){throw new Tt(y)}let R=r.mode==="no-cors",I=n.type==="successful-write"?300:400;if(!R&&(h.status<200||h.status>=I))throw new xe(h,a,p,l);if(n.type==="successful-write"){try{await Promise.race([w(),m])}catch{}return}try{return await Promise.race([n.consume(h),m])}catch(y){throw l.signal.aborted?new Tt(y):y}}finally{clearTimeout(g),l.signal.aborted&&h&&w()}},{...c,retryCheck:l=>{let d=c.retryCheck(l);return d&&u<=c.retryCount&&l instanceof xe&&l.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:$t((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(!cM(s))throw s;await Qh(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 gM=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var rW=new RegExp(gM.source,"i"),s_=/[a-z][a-z0-9+.-]{0,63}:\/\//i,nW=new RegExp(`^${s_.source}`,"i"),sW=new RegExp(s_.source,"gi");var mM=["is_not","is_set"],hM=1152921504606847e3,O=class t extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,t.prototype)}};function tl(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(!tl(e in t?t[e]:null))return!1;return!0}function rl(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(!rl(e in t?t[e]:null))return!1;return!0}function is(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 O("Cannot stringify an unpaired surrogate like the flags service");e++}else if(r>=56320&&r<=57343)throw new O("Cannot stringify an unpaired surrogate like the flags service")}}function Ai(t,e=new Set){if(!(t===null||typeof t=="boolean")){if(typeof t=="string")return void is(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new O(`Cannot represent non-finite number ${t} like the flags service`);return}if(Array.isArray(t)){if(e.has(t))throw new O("Cannot represent a circular array during local evaluation");e.add(t);try{for(let r=0;r<t.length;r++)r in t&&Ai(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 O("Cannot represent a non-JSON object like the flags service");if(e.has(t))throw new O("Cannot represent a circular object during local evaluation");e.add(t);try{for(let n of Object.keys(t))is(n),Ai(t[n],e)}finally{e.delete(t)}return}throw new O(`Cannot represent ${typeof t} like the flags service`)}}function _M(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 nl(t,e=new Set){if(t===null)return"null";if(typeof t=="string")return is(t),JSON.stringify(t);if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new O(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new O(`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 O("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?nl(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 O("Cannot stringify a non-JSON object like the flags service");if(e.has(t))throw new O("Cannot stringify a circular object during local evaluation");e.add(t);try{let n=Object.keys(t);return n.forEach(is),`{${n.sort(_M).map(s=>`${JSON.stringify(s)}:${nl(t[s],e)}`).join(",")}}`}finally{e.delete(t)}}throw new O(`Cannot stringify ${typeof t} like the flags service`)}function Ri(t){return typeof t=="string"?(is(t),t):nl(t)}function o_(t){try{return new RegExp(t),!0}catch{return!1}}function Ne(t){return String(t).replace(/[A-Z]/g,e=>e.toLowerCase())}function a_(t,e,r){if(!/^\d+$/.test(t)||r==="strict"&&t.length>1&&t[0]==="0")throw new O(`Invalid semver: ${e}`);return parseInt(t,10)}function Z(t,e="strict"){let n=String(t).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new O(`Invalid semver: ${t}`);let s=n.split("."),o=i=>i===void 0||i===""?0:a_(i,t,e);return[o(s[0]),o(s[1]),o(s[2])]}function Ce(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 EM(t,e){let r=Z(t,e);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function SM(t,e){let[r,n,s]=Z(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 yM(t,e){let n=String(t).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new O(`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 a_(c,t,e)}catch{}throw new O(`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 i_(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 O(`${t} is in an invalid date format`)}throw new O(`The date provided ${t} must be a string, number, or date object`)}function sl(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 ol(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 O(`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&&!mM.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&&tl(d)||Array.isArray(d)&&d.length===0)return Ai(p),rl(d)===rl(p);if(r.propertyMatchingVersion===2&&typeof p=="number"&&tl(d))return Ai(p),!1;if(Array.isArray(d)){let g=Ri(p).toLowerCase();return d.some(m=>Ri(m).toLowerCase()===g)}return Ri(d).toLowerCase()===Ri(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 Ne(c).includes(Ne(s));case"not_icontains":return!Ne(c).includes(Ne(s));case"starts_with":return Ne(c).startsWith(Ne(s));case"not_starts_with":return!Ne(c).startsWith(Ne(s));case"ends_with":return Ne(c).endsWith(Ne(s));case"not_ends_with":return!Ne(c).endsWith(Ne(s));case"regex":return o_(String(s))&&String(c).match(String(s))!==null;case"not_regex":return o_(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 O("Date operations cannot be performed on boolean values");let d=sl(String(s));d==null&&(d=i_(s));let p=i_(c);return o==="is_date_before"?p<d:p>d}case"semver_eq":return Ce(Z(String(c),i),Z(String(s),i))===0;case"semver_neq":return Ce(Z(String(c),i),Z(String(s),i))!==0;case"semver_gt":return Ce(Z(String(c),i),Z(String(s),i))>0;case"semver_gte":return Ce(Z(String(c),i),Z(String(s),i))>=0;case"semver_lt":return Ce(Z(String(c),i),Z(String(s),i))<0;case"semver_lte":return Ce(Z(String(c),i),Z(String(s),i))<=0;case"semver_tilde":{let d=Z(String(c),i),{lower:p,upper:g}=EM(String(s),i);return Ce(d,p)>=0&&Ce(d,g)<0}case"semver_caret":{let d=Z(String(c),i),{lower:p,upper:g}=SM(String(s),i);return Ce(d,p)>=0&&Ce(d,g)<0}case"semver_wildcard":{let d=Z(String(c),i),{lower:p,upper:g}=yM(String(s),i);return Ce(d,p)>=0&&Ce(d,g)<0}default:throw new O(`Unknown operator: ${o}`)}}async function c_(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 as(t,e,r="",n="."){let s=await c_(`${t}${n}${e}${r}`);return parseInt(s.slice(0,15),16)/hM}async function il(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 as("holdout",e,"","-")>n/100))return`holdout-${t.id}`}function Mi(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 al(t,e,r){let n=await as(t,e,"variant");return Mi(r).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function cl(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:Yr(n)}var u_=9223372036854776e3,bM="9223372036854775808",wM=Object.prototype.propertyIsEnumerable;function TM(){return{ancestors:new WeakSet,remainingNodes:1e4}}function pt(t,e){try{return l_(t,e,TM(),0)}catch{return[]}}function IM(t,e){let r=t.toString(),n=BigInt(bM);return t>=n||t<-n?(e?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function dl(t,e,r,n){if(r.remainingNodes<=0)return{stringValue:Si};if(r.remainingNodes--,ih(t))return{boolValue:t};if(typeof t=="bigint")return IM(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>=u_||t<-u_?(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:dt(t)};if(typeof t=="function")return{stringValue:Mh};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(r.ancestors.has(t))return{stringValue:Ei};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"?dt(o):String(o)}}r.ancestors.add(t);try{try{let s=t.toJSON;if(typeof s=="function")return dl(s.call(t),e,r,n+1)}catch{}return Te(t)?{arrayValue:{values:vM(t,e,r,n+1)}}:{kvlistValue:{values:l_(t,e,r,n+1)}}}finally{r.ancestors.delete(t)}}return{stringValue:dt(String(t))}}function vM(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(Ze(a))continue;s.push(dl(a,e,r,n))}catch{s.push({stringValue:ke})}return t.length>i&&s.push({stringValue:Si}),s}function l_(t,e,r,n){let s=[];for(let o in t)if(wM.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(Ou(i)||bt(i))continue;s.push({key:dt(o),value:dl(i,e,r,n)})}catch{s.push({key:dt(o),value:{stringValue:ke}})}}return s}function us(t,e,r){return{...wt({},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 RM=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function ls(t,e){let r=wt({},t),n={};for(let s of RM)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s],delete r[s]);return[...pt(r,e),...pt(n,e)]}var d_={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 AM(t){if(t)return Object.prototype.hasOwnProperty.call(d_,t)?d_[t]:t}function fl(t,e){let r=AM(t);return{...r?{"os.name":r}:{},...e?{"os.version":e}:{}}}var MM={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}},yW=MM.info;var pr=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 ds(){return 1-.25+Math.random()*.25*2}var De=1;function fs(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 pl="0000000000000000",xM=pl+pl,NM=/^[0-9a-f]+$/;function CM(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 DM(t){let e="";for(let r=0;r<t.length;r++)e+=t[r].toString(16).padStart(2,"0");return e}function f_(t){let e=DM(CM(t));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function p_(){return f_(16)}function g_(){return f_(8)}function m_(t,e,r){return typeof t=="string"&&t.length===e&&t!==r&&NM.test(t)}function h_(t){return m_(t,32,xM)}function __(t){return m_(t,16,pl)}var FM=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Pi(t){let e=E_(t);return e&&{traceId:e.traceId,spanId:e.spanId,flags:LM(e.flags)}}function LM(t){return 1&parseInt(t,16)?Jr:UM}function E_(t){if(typeof t!="string")return;let e=FM.exec(t.trim());if(!e)return;let[,r,n,s,o,i]=e;if(r!=="ff"&&!(r==="00"&&i)&&!(!h_(n)||!__(s)))return{version:r,traceId:n,spanId:s,flags:o}}function S_(t){return E_(t)&&t.trim()}function ki(t){return Array.isArray(t)&&t.length===1?t[0]:t}var Jr="01",UM="00";function y_(t,e,r=Jr){return`00-${t}-${e}-${r}`}var $M=32,gl=512;function xi(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>$M)){for(let n of r)if(n.trim()&&!n.includes("="))return;return e.length<=gl?e:WM(r)}}var BM=128;function WM(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()>gl;n--)e[n].length>BM&&e.splice(n,1);for(;e.length&&r()>gl;)e.pop();return e.length?e.join(","):void 0}var ps=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ni(t){return String(t)+"000000"}function ml(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 b_(t,e){for(let r=0;r<e.length;r++)if(t<=e[r])return r;return e.length}function hl(t,e,r){return us(t,e,r)}function _l(t,e,r,n){return{resourceMetrics:[{resource:{attributes:ls(e)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]}}function Ci(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 w_=1,gs=class{constructor(e,r,n){this._instance=e,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new pr(()=>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 dr,this._consecutiveFlushFailures=0,this._flushJitter=De,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=De,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=ml(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=Pi(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Jr)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(ps.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[b_(r,ps)]+=1;break}}}_runBeforeSend(e){let r=this._config.beforeSend;if(!r)return e;let n=Te(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(fs(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=ds()):(this._consecutiveFlushFailures=0,this._flushJitter=De),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 _l(this._buildMetrics(e),hl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let r=Ni(Date.now()),n=new Map;for(let s of e.values()){let o=ml(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:w_,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?i.gauge={dataPoints:[]}:i.histogram={aggregationTemporality:w_,dataPoints:[]},n.set(o,i));let a=pt(s.attributes??{},this._logger),c=Ni(s.windowStartMs),u=jM(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:ps,...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 jM(t){return t?{exemplars:[{filteredAttributes:[],timeUnixNano:Ni(t.timeMs),asDouble:t.value,traceId:t.traceId,spanId:t.spanId}]}:{}}var T_="unknown";function gr(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 "${T_}"`),T_)}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 I_(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 Di(t,e){return t<e?e:t}function ms(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 Li(){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??Jr,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:Li(),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=Li();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(Ze(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]=$i(r,this._maxAttributeValueLength)}setAttribute(e,r){return this._mutable("setAttribute")&&this._writeAttribute(e,r),this}setAttributes(e){if(this._mutable("setAttributes")){let r=wt({},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&&M_(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:gr(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:ms(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:El(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}=Sl(e);return this.addEvent(HM,{"exception.type":r,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=gr(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return y_(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=ms(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:Di(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},HM="exception",XM=4294967295;function KM(t){try{return typeof t=="string"?t:String(t)}catch{return ke}}function mr(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:Math.min(Math.floor(t),XM)}function GM(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 R_(t,e,r,n,s,o,i=[]){let a=0,c=0,u={};for(let g of GM(t.attributes,i)){let m=t.attributes[g];if(!Ze(m)){if(!e.has(g)){if(a>=r){c++;continue}a++}Object.defineProperty(u,g,{value:$i(m,o),enumerable:!0,writable:!0,configurable:!0})}}t.attributes=u,c&&(t.droppedAttributesCount=mr(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=M_(g.attributes,s,o);g.attributes=m.attributes,m.dropped&&(g.droppedAttributesCount=mr(g.droppedAttributesCount)+m.dropped)}p.push(g)}t.events=p,d&&(t.droppedEventsCount=mr(t.droppedEventsCount)+d),t.status?.message&&(t.status={...t.status,message:El(KM(t.status.message),o)})}var Ui=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(){}},A_=new Ui,hs=class extends Ui{constructor(e,r){super(),this._traceparent=e,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function zM(t){try{let e=t.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Bt(t,e){let r=ki(t?.parent)??e,n=typeof r=="string"||r==null?r:v_(r,"traceparent"),s=S_(n);if(!s)return A_;let o=typeof r=="string"||r==null?t?.tracestate:v_(r,"tracestate");return new hs(s,xi(o))}function v_(t,e){try{let r=t[e];return typeof r=="function"?r.call(t):void 0}catch{return}}function El(t,e){return t.length>e?t.slice(0,e):t}function $i(t,e){return Fi(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Fi(t,e,r,n){if(t===null||typeof t!="object")return Ze(t)||r.remainingNodes<=0?t:(r.remainingNodes--,typeof t=="string"?El(t,e):t);if(r.ancestors.has(t))return Ei;if(r.remainingNodes<=0||n>=20)return t;r.remainingNodes--,r.ancestors.add(t);try{if(t instanceof Date)return t;let s=VM(t);if(s.selfDescribed)return Ze(s.value)?String(s.value):Fi(s.value,e,r,n+1);if(Te(t)){let a=Math.min(t.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(Fi(t[u],e,r,n+1))}catch{c.push(ke)}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=Fi(t[a],e,r,n+1)}catch{c=ke}a&&!Ze(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 VM(t){try{let e=t.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(t)}}catch{}return{selfDescribed:!1}}function M_(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=$i(t[a],r)}catch{c=ke}Ze(c)||(o++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:i}}function O_(t,e){for(let r of Object.keys(t))t[r]=$i(t[r],e);return t}function _s(t,e,r){return e===A_?r(e):t.with(e,()=>r(e))}function Sl(t){try{let e=zM(t);if(Ut(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 yl={internal:1,server:2,client:3,producer:4,consumer:5},YM={ok:1,error:2},qM=1,JM=256,ZM=512;function QM(t){let e=parseInt(t.traceFlags,16);return(Number.isFinite(e)?255&e:qM)|JM|(t.parentIsRemote?ZM:0)}function Bi(t){if(typeof t=="string")return dt(t);try{return dt(String(t))}catch{return ke}}function eO(t){return t&&Object.prototype.hasOwnProperty.call(yl,t)?yl[t]:yl.internal}function bl(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 tO(t,e){let r={name:Bi(t.name),timeUnixNano:bl(t.timestamp)};if(t.attributes){let s=pt(t.attributes,e);s.length&&(r.attributes=s)}let n=mr(t.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function P_(t,e){let r={traceId:t.traceId,spanId:t.spanId,name:Bi(t.name),kind:eO(t.kind),startTimeUnixNano:bl(t.startTime),endTimeUnixNano:bl(t.endTime),flags:QM(t)};t.parentSpanId&&(r.parentSpanId=t.parentSpanId),t.traceState&&(r.traceState=Bi(t.traceState));let n=pt(t.attributes,e);n.length&&(r.attributes=n),t.events.length&&(r.events=t.events.map(i=>tO(i,e)));let s=mr(t.droppedAttributesCount);s&&(r.droppedAttributesCount=s);let o=mr(t.droppedEventsCount);return o&&(r.droppedEventsCount=o),t.status&&(r.status={code:YM[t.status.code],...t.status.message&&{message:Bi(t.status.message)}}),r}function k_(t,e,r){return us(t,e,r)}function x_(t,e,r,n,s){return{resourceSpans:[{resource:{attributes:ls(e,s)},scopeSpans:[{scope:{name:r,version:n},spans:t}]}]}}var N_=8;function Wi(){return Li()??Date.now()}function wl(t){try{return t instanceof Qr}catch{return!1}}function C_(t,e){let r=Pi(t);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:xi(e),traceFlags:r.flags,isRemote:!0}}function rO(t){try{return typeof t.traceparent=="function"}catch{return!1}}function nO(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 ji(t,e,r){t[e]!==r&&(t[e]=r)}function sO(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 Es=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 pr(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=De,this._retryAfter=new dr,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 Bt(r,this._contextManager.active());let n=ki(r?.parent);if(n&&typeof n!="string"&&!wl(n)){if(rO(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Bt(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`),Bt(r,this._contextManager.active());let o=Date.now(),i=I_(r?.startTime,o,this._logger),a=g_();this._liveSpans.set(a,Wi());let c=this._autoContextAttributes();return new Qr({traceId:s?.traceId??p_(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:gr(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:wt({...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=_s(this._contextManager,i,o);return xh(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=De,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,r){if(typeof e=="string"){let s=C_(e,r?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(wl(e))return e.childContext();let n=this._contextManager.active();if(wl(n))return n.childContext();if(n instanceof hs)return C_(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}=Sl(r);e.addEvent("exception",{"exception.type":n,"exception.message":s,...o&&{"exception.stacktrace":o}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=Wi()-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},!nO(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=gr(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=Di(Zr(l.endTime)??s.endTime,l.startTime);let p=[];for(let g of l.events)try{p.push({...g,name:gr(g.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:ms(g.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=p,R_(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{ji(e,"traceId",r.traceId),ji(e,"spanId",r.spanId),ji(e,"parentSpanId",r.parentSpanId),ji(e,"traceState",r.traceState)}catch{return sO(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(P_(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=O_(k_(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=Wi()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(x_(g,r,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=De,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=De,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=ds(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=Wi()+this._nextFlushDelay()),this._headBatchFailures<N_)return this._logger.debug("Span export failed; retrying on the next flush",h.error),i;if(this._queue.splice(0,d),o-=d,i+=d,this._consecutiveFlushFailures=0,this._flushJitter=De,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${N_} times in a row`),this._retryAfter.isOpen())return i;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",h.error),this._queue.splice(0,d),o-=d,i+=d,this._consecutiveFlushFailures=0,this._flushJitter=De,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(fs(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var Ss=class{active(){return this._active}with(e,r){let n=this._active;this._active=e;try{return r()}finally{this._active=n}}};var oO=5e3,iO=512,aO=2048,cO=128,uO=128,lO=128,dO=8192,fO=1e4,pO=36e5;function Wt(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:e}var D_=["service.name","service.version","deployment.environment"];function gO(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{if(D_.every(r=>!(r in t)||typeof t[r]=="string"))return t;let e={...t};for(let r of D_)r in e&&typeof e[r]!="string"&&delete e[r];return e}catch{return}}function mO(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 Tl(t,e,r){let n=wt({...e},gO(t?.resourceAttributes)),s=Wt(t?.maxExportBatchSize,iO);return{serviceName:n?.["service.name"]??t?.serviceName,serviceVersion:n?.["service.version"]??t?.serviceVersion,environment:n?.["deployment.environment"]??t?.environment,resourceAttributes:n,beforeSpanSend:mO(t?.beforeSpanSend,r),maxAttributesPerSpan:Wt(t?.maxAttributesPerSpan,cO),maxEventsPerSpan:Wt(t?.maxEventsPerSpan,uO),maxAttributesPerEvent:lO,maxAttributeValueLength:Wt(t?.maxAttributeValueLength,dO),flushIntervalMs:Wt(t?.flushIntervalMs,oO),maxExportBatchSize:s,maxQueueSize:Math.max(Wt(t?.maxQueueSize,aO),s),maxLiveSpans:Wt(t?.maxLiveSpans,fO),maxSpanAgeMs:Wt(t?.maxSpanAgeMs,pO)}}var Il=require("node:fs"),U_=require("node:fs/promises"),Rl=require("node:path"),$_=require("node:readline"),Hi=new ee.ReduceableCache(25),ys=new ee.ReduceableCache(20),Al=7,hO=1e3,_O=1e4,vl=10485760;async function B_(t,e=U_.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"||wO(u)||TO(c)||!(0,Rl.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=W_(a,s);if(c===void 0||ys.get(c))continue;let u=n[a];if(!u)continue;u.sort((p,g)=>p-g);let l=vO(u);if(l.every(p=>IO(c,p)))continue;let d=RO(Hi,c,{});i.push(SO(a,l,d,c,e,r))}return await Promise.all(i).catch(()=>{}),t&&t.length>0&&yO(t,Hi,s),Hi.reduce(),t}async function EO(t,e,r){let n,s=!1;try{n=await e(t,Il.constants.O_RDONLY|Il.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>vl?void r?.debug(`Skipping source context for oversized file ${t}: ${o.size} bytes exceeds ${vl}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function SO(t,e,r,n,s,o){let i=await EO(t,s,o);if(i===void 0)return void ys.set(n,1);let a=i;return new Promise(c=>{let u=!1;function l(T){u||(u=!0,T?.destroy(),a.close().then(c,c))}let d;try{d=a.createReadStream({autoClose:!1,start:0,end:vl-1})}catch{ys.set(n,1),l();return}let p;try{p=(0,$_.createInterface)({input:d})}catch{ys.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 w(){ys.set(n,1),p.close(),p.removeAllListeners(),l(d)}d.on("error",w),p.on("error",w),p.on("close",()=>l(d)),p.on("line",T=>{if(g++,!(g<_)&&(r[g]=AO(T,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 yO(t,e,r){for(let n of t)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=W_(n.filename,r),o=s===void 0?void 0:e.get(s);if(o===void 0)continue;bO(n.lineno,n,o)}}function bO(t,e,r){if(e.lineno===void 0||r===void 0)return;e.pre_context=[];for(let s=j_(t);s<t;s++){let o=r[s];if(o===void 0)return void F_(e);e.pre_context.push(o)}if(r[t]===void 0)return void F_(e);e.context_line=r[t];let n=H_(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 F_(t){delete t.pre_context,delete t.context_line,delete t.post_context}function wO(t){return t.startsWith("node:")||t.endsWith(".min.js")||t.endsWith(".min.cjs")||t.endsWith(".min.mjs")||t.startsWith("data:")}function TO(t){return t.lineno!==void 0&&t.lineno>_O||t.colno!==void 0&&t.colno>hO}function W_(t,e){return(0,Rl.isAbsolute)(t)?JSON.stringify([null,t]):e===void 0?void 0:JSON.stringify([e,t])}function IO(t,e){let r=Hi.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 vO(t){if(!t.length)return[];let e=0,r=t[0];if(typeof r!="number")return[];let n=L_(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+Al:(s.push(n),n=L_(o)),e++}return s}function L_(t){return[j_(t),H_(t)]}function j_(t){return Math.max(1,t-Al)}function H_(t){return t+Al}function RO(t,e,r){let n=t.get(e);return n===void 0?(t.set(e,r),r):n}function AO(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 en=require("path");function X_(t=process.cwd()){let e=en.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,en.isAbsolute)(o.filename)&&(o.filename=r((0,en.relative)(n,r(o.filename))));return s}}var K_="5.56.2";var It={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var jt=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(It.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(It.QUOTA_LIMITED),r===void 0&&o.push(It.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 G_(t){return t==="client"||t==="server"?t:"all"}function OO(t,e){return t===e||t==="all"||e==="all"}var hr=class t extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t.prototype)}};function PO(t,e){t.name=e.name,Error.captureStackTrace(t,e),Object.setPrototypeOf(t,e.prototype)}var gt=class t extends Error{constructor(e){super(e),PO(this,t)}},Xi=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 gt||u instanceof O?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 gt||u instanceof O?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=cl(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 O("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 O("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 O(`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 O("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new O(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let i=e.dependency_chain;if(!Array.isArray(i))throw new O(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof i})`);if(i.length===0)throw new O(`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 O(`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 O(`Missing flag dependency '${c}' for flag '${o}'`)}if(s[c]==null)throw new O(`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 il(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 T=s.definitions.groupTypeMapping[String(h)];if(!T||!(T in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(T in d)){p=!0;continue}_=d[T],S=l[T]}let w=await this.isConditionMatch(e,S,m,_,s);if(w==="match"){let T=m.variant,R=o.multivariate?.variants||[];g=T&&R.some(I=>I.key===T)?T:await this.getMatchingVariant(e,S)||!0;break}if(u&&w==="out_of_rollout_bound"){if(p)break;return!1}}catch(h){if(h instanceof gt)throw h;if(h instanceof O)p=!0;else throw h}if(g!==void 0)return g;if(p)throw new O("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 V_(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):z_(u,s,c,i.propertyMatchingVersion);if(!d)return"no_match"}if(a==null)return"match"}return a!=null&&await as(e.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,r){return al(e.key,r,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return Mi(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?G_(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(r=>OO(G_(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 hr(`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 hr(`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 hr(`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 hr&&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 hr("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 $t(r,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function z_(t,e,r,n){return ol(t,e,{warnFunction:r,propertyMatchingVersion:n})}function kO(t,e){if(!(t in e))throw new gt(`cohort ${t} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function V_(t,e,r,n=!1,s,o){let i=String(t.value);kO(i,r);let a=r[i];return Y_(a,e,r,n,s,o)}async function Y_(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 Y_(u,e,r,n,s,o);if(i==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof gt)throw l;if(l instanceof O)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new O("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 V_(u,e,r,n,s,o);else if(u.type==="flag"){if(!s)throw new O(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await s(u)}else l=z_(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 gt)throw l;if(l instanceof O)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new O("can't match cohort without a given cohort property value");return i==="AND"}var xO=["--unhandled-rejections","--unhandled_rejections"],NO=new Set(["throw","strict","warn","warn-with-error-code","none"]),CO=[...globalThis.process?.execArgv??[]],DO=globalThis.process?.env?.NODE_OPTIONS;function FO(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 q_(t){let e;for(let r=0;r<t.length;r++){let n=t[r],s=xO.find(i=>n===i||n.startsWith(`${i}=`));if(!s)continue;let o=n===s?t[++r]:n.slice(s.length+1);NO.has(o)&&(e=o)}return e}function LO(t=CO,e=DO){return q_(t)??q_(FO(e??""))??"throw"}var J_=LO();function Z_(t,e,r){t(e,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function UO(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;Z_(t,n,s),!r&&o===0&&(r=!0,e(n))},{_posthogErrorHandler:!0})}function Q_(t,e,r=J_){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(s,o)=>Z_(t,s,o));n.on("uncaughtException",UO(t,e))}}function eE(t,e=J_){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 $O=2e3,Ml=class t{constructor(e,r,n){this.client=e,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new li({...dh(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()&&(Q_(this.onException.bind(this),this.onFatalError.bind(this)),eE(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($O),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},_r=Ml;var EP=/^[0-9a-f]{32}$/i,SP=/^[0-9a-f]{16}$/i,yP;async function CS(){try{let e=(await(yP??=Promise.resolve().then(()=>(NS(),xS)))).trace.getActiveSpan()?.spanContext(),r=e?.traceId,n=e?.spanId;if(typeof r=="string"&&typeof n=="string"&&EP.test(r)&&SP.test(n)&&!/^0+$/.test(r)&&!/^0+$/.test(n))return{$trace_id:r.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var ia=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,r){this._memoryStorage[e]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function bP(t){return t==="v0"||t==="v1"}function DS(){let t="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return bP(t)?t:"v0"}var wP="$ai_",As="analytics";function FS(t){return typeof t.event=="string"&&t.event.startsWith(wP)}var nn=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 pd(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 TP(t){return typeof t=="string"?t:void 0}var IP=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:pd},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:pd},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:pd},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:TP}],vP=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function RP(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function AP(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 LS(t,e,r){r!==void 0&&!(e in t)&&(t[e]=r)}function MP(t){let r={...RP(t.properties)?t.properties:{}},n={};for(let{property:o,optionKey:i,coerce:a}of IP)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 vP)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,LS(r,"$set",t.$set),LS(r,"$set_once",t.$set_once),{event:String(t.event??""),uuid:String(t.uuid??""),distinct_id:String(t.distinct_id??""),timestamp:AP(t.timestamp),...s,options:n,properties:r}}function US(t,{createdAt:e,historicalMigration:r}){let n={created_at:e,batch:t.map(MP)};return r&&(n.historical_migration=!0),n}var OP="/i/v1/analytics/events",PP=3e4,kP=new Set([408,500,502,503,504]),aa=class{constructor(e,r){this.config=e,this.maxBackoffMs=e.maxBackoffMs??PP,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??ss}async sendV1Batch(e){if(e.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=US(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${OP}`,i=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,d=Lt({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&&kP.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 w=this.classify(a,S,i);if(w.length===0)return this.surfacePartialDrops(r,i);if(l)return void this.onError(new nn({requestId:r,drops:i,retryExhausted:w.map(R=>R.uuid)}));a=w;let T=this.parseRetryAfter(m);g=this.backoffDelay(u,T)}}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 nn({requestId:e,drops:r,retryExhausted:n.map(o=>o.uuid),cause:s}))}surfacePartialDrops(e,r){r.length>0&&this.onError(new nn({requestId:e,drops:r,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var Er="ai-capture",ca="/i/v0/ai/batch/";var NP=new TextEncoder;function md(t){return NP.encode(Lt(t)).length}function $S(t,e=8388608,r=5242880){let n=[],s=[],o=[],i=0;for(let a of t){if(a===void 0)continue;let c=md(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 CP=100,BS=3e4,DP=5e4,FP=50,LP=500,UP="https://us.i.posthog.com",WS=new Set;function la(t,e){WS.has(t)||(WS.add(t),console.warn(`[PostHog] ${e}`))}function $P(t){return typeof t=="string"?t.trim():""}function BP(t){return(typeof t=="string"?t.trim():"")||void 0}function WP(t){return(typeof t=="string"?t.trim():"")||UP}function jP(t){return(Array.isArray(t)?t:[t]).filter(r=>typeof r=="string"&&r.trim().length>0)}function HP(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 da=class extends os{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,r={}){let n=$P(e),s={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:WP(r.host),personalApiKey:BP(r.secretKey??r.personalApiKey)};if(super(n,s),this._memoryStorage=new ia,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=DS(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,CP):s.featureFlagsPollingInterval===null?null:BS,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 Xi({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 _r(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||DP}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:Vn([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??LP,s=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??FP;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"&&FS(e)?"ai":As}persistedQueueKeyForRoute(e){return e===Er?he.AiCaptureQueue:e==="ai"?he.AiQueue:he.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[As,"ai"]:[As];return this._aiCaptureRouteActive&&e.push(Er),e}getBatchEndpointPath(e){return e===Er?ca:super.getBatchEndpointPath(e)}async sendBatch(e,r,n=As){if(n===Er)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}=$S(e);for(let{event:o,bytes:i}of s){let a=`Event ${o} (${i} bytes) exceeds the ${8388608/1048576}MiB limit for ${ca}, 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,Er)}catch(n){if(!qr(n))throw n;if(e.length===1){let[o]=e,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${md(o)} bytes) was rejected with 413 by ${ca} 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 aa({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 K_}get metrics(){return this._metrics||(this._metrics=new gs(this,Ci(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new Ss}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 Es(this,Tl(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)??Bt(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):_s(this._spanContextManager,Bt(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=fr(e.uuid,fe);return this._sendPreparedAiEvent({...e,uuid:r},!1),r}async captureAiImmediate(e){if(this.disabled)return;let r=fr(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,Er)}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=jP(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=BS){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 A=this._payloadOverrides?.[e];return{key:e,enabled:v!==!1,variant:typeof v=="string"?v: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,w,T,R,I;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let v=this.featureFlagsPoller?.featureFlagsByKey[e];if(v)try{let A=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(v,p,{matchValue:s});if(A){m=!0;let b=A.value;w=v.id,R="Evaluated locally",I=v.has_experiment,g={key:e,enabled:b!==!1,variant:typeof b=="string"?b:void 0,payload:A.payload??void 0,reason:R,reasonCode:v.active===!1?"flag_disabled":void 0}}}catch(A){if(A instanceof gt||A instanceof O)this._logger?.info(`${A.name} when computing flag locally: ${e}: ${A.message}`);else throw A}}if(!m&&!c){let v=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,a,[e]);if(v===void 0)S=It.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,h=v.requestId,_=v.evaluatedAt;let A=[];v.errorsWhileComputingFlags&&A.push(It.ERRORS_WHILE_COMPUTING),v.quotaLimited?.includes("feature_flags")&&A.push(It.QUOTA_LIMITED);let b=v.flags[e];if(b===void 0)A.push(It.FLAG_MISSING);else{w=b.metadata?.id,T=b.metadata?.version,R=b.reason?.description??b.reason?.code,I=b.metadata?.has_experiment;let P;if(b.metadata?.payload!==void 0)try{P=JSON.parse(b.metadata.payload)}catch{P=b.metadata.payload}g={key:e,enabled:b.enabled,variant:b.variant??void 0,payload:P,reason:R,reasonCode:b.reason?.code}}A.length>0&&(S=A.join(","))}}if(o){let v=g===void 0?void 0:g.enabled===!1?!1:g.variant??!0,A={$feature_flag:e,$feature_flag_response:v,$feature_flag_id:w,$feature_flag_version:T,$feature_flag_reason:R,locally_evaluated:m,[`$feature/${e}`]:v,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():_};if(I!==void 0&&(A.$feature_flag_has_experiment=I),m&&this.featureFlagsPoller){let b=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();b!==void 0&&(A.$feature_flag_definitions_loaded_at=b)}S&&(A.$feature_flag_error=S),this._captureFlagCalledEventIfNeeded({distinctId:r,key:e,response:v,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){la("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(la("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){la("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 jt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new jt({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:i}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new jt({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,w=!1,T=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),R=new Set;if(T)for(let[v,A]of Object.entries(T.response)){let b=this.featureFlagsPoller?.featureFlagsByKey[v];m[v]={key:v,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:T.payloads[v],id:b?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:b?.has_experiment},R.add(v)}let I=g!==void 0&&Array.from(g).some(v=>this.featureFlagsPoller?.featureFlagsByKey[v]===void 0);if((T?T.fallbackToFlags||I:!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,w=Array.isArray(v.quotaLimited)&&v.quotaLimited.includes("feature_flags");for(let[A,b]of Object.entries(v.flags)){if(R.has(A))continue;let P;if(b.metadata?.payload!==void 0)try{P=JSON.parse(b.metadata.payload)}catch{P=b.metadata.payload}m[A]={key:A,enabled:b.enabled,variant:b.variant,payload:P,id:b.metadata?.id,version:b.metadata?.version,reason:b.reason?.description??b.reason?.code,locallyEvaluated:!1,hasExperiment:b.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[v,A]of Object.entries(this._flagOverrides)){if(A===void 0){delete m[v];continue}let b=m[v];m[v]={key:v,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:b?.payload,id:b?.id,version:b?.version,reason:b?.reason,locallyEvaluated:b?.locallyEvaluated??!1,hasExperiment:b?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[v,A]of Object.entries(this._payloadOverrides)){let b=m[v];b&&(m[v]={...b,payload:A})}if(g!==void 0)for(let v of Object.keys(m))g.has(v)||delete m[v];return new jt({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:i,flags:m,requestId:h,evaluatedAt:_,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:S,quotaLimited:w})}_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 $t(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await $t(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(ch(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(!_r.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");this.addPendingPromise(_r.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(!_r.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(_r.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 CS()),m||(m=fe(),h.$process_person_profile=!1),g&&p?.sessionId&&!h.$session_id&&(h.$session_id=p.sessionId);let _=this._shouldSendMinimalFlagCalledEvent(s,h)?rs(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 w=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){la("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 T=typeof c=="object"?c:void 0,R=await this.getFeatureFlagsForEvent(S.distinctId,i,l,T);return HP(R)}return{}}).catch(()=>({})).then(T=>{let R=S.groups||i;return{...T,...S.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return S.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof w.$raw_user_agent=="string"&&lh(w.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(S.event="$bot_pageview",w.$browser_type="bot"),{distinctId:S.distinctId,event:S.event,properties:w,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 jS=require("node:async_hooks"),fa=class{constructor(){this.storage=new jS.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 HS=require("node:async_hooks"),pa=class{active(){return this._storage.getStore()}with(e,r){return this._storage.run(e,r)}constructor(){this._storage=new HS.AsyncLocalStorage}};var XS=require("node:zlib"),KS=require("node:util"),XP=(0,KS.promisify)(XS.gzip);async function GS(t,e=!0){try{let r=await XP(t);return new Uint8Array(r)}catch(r){return e&&console.error("Failed to gzip compress data",r),null}}var ga=require("node:os");function zS(){let t,e;try{t=(0,ga.platform)(),e=(0,ga.release)()}catch{}return fl(t,e)}var VS="posthog-node";function KP(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[hd.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 hd=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,r,n,s,o){this.name=VS,this.name=VS,this.setupOnce=function(i,a){let c=a()?.getClient()?.getDsn()?.projectId;i(KP(e,{organization:r,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:o??!0}))}}};var ma=class extends da{getLibraryId(){return"posthog-node"}compressPayload(e){return GS(e,this.isDebug)}initializeContext(){return new fa}initializeSpanContextManager(){return new pa}hostResourceAttributes(){return zS()}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),[nh(),e=>B_(e,void 0,this._logger),X_()])}};bc();Rc();vc();Mc();var RG=300*1e3,AG=3600*1e3;M();var Ed=null,GP=!1,zP=3e4,ha=null;function qS(){let t=Date.now();if(ha&&t<ha.expiresAt)return ha.value;let e=go(process.env,bn());return ha={value:e,expiresAt:t+zP},e}var VP=!1;function YP(){if(!Ed){let t=VP&&pp(process.env)&&qS();Ed=new ma(_o(),{host:Eo(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:t,before_send:sk})}return Ed}var qP=6e4,JP=500,Ms=new Map;function ZP(t,e,r){let n="";try{let s=(r||"").split(`
43
- `).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}::${Sp(e)}::${n}`.slice(0,400)}function QP(t,e){try{return ek(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 ek(t,e){let r=Ms.get(t);if(!r){if(Ms.size>=JP){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>=qP){r.lastSentTs=e;let n=r.count;return r.count=0,{send:!0,count:n}}return{send:!1,count:r.count}}var YS="__cm_rate_limited";function tk(t){try{return typeof t!="string"||t.length===0?"":Tc(wc(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 rk(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=Ep(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=tk(a.filename))}}}function nk(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 sk(t){try{if(!t||typeof t!="object")return t;let e=t;if(e.event!=="$exception")return t;let r=e.properties??{};if(nk(r))return null;if(r[YS]){try{delete r[YS],e.properties=r}catch{}return t}rk(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=ZP(n,s,o),a=QP(i,Date.now());if(!a.send)return null;try{r.occurrence_count=a.count,e.properties=r}catch{}return t}catch{return null}}function _d(t,e,r){try{ok(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 ok(t,e,r){if(GP||!qS())return;let n=ho({...yo(),...e??{}});if(r?.person?n.$set=So(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
44
- `);return}YP().capture({distinctId:mo(),event:t,properties:n})}var ik=["cloud-sync","distill","handoff","how-it-works","import-chats","import-jira","import-reviews","knowledge-agent","mem-search","mode-creator","pin","savings","timeline-report","weekly-digests"],ak=new Set(ik),JS={skill_id:"other",skill_source:"third_party"};function ZS(t){let e=ck(t);return e&&ak.has(e)?{skill_id:e,skill_source:"first_party"}:JS}function QS(t,e){if(t==="Skill"&&!(!e||typeof e!="object"))return e.skill}function ck(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}M();ut();function uk(t){return["false","0","off","no"].includes(String(t??"").trim().toLowerCase())}function lk(t){return["true","1","on","yes"].includes(String(t??"").trim().toLowerCase())}function Sd(t){return!uk(t.MEMINDEX_OBSERVER_ENABLED)}function ey(t){return lk(t.MEMINDEX_DISABLE_SUMMARY)}Ea();var ry=null,fk=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),ny=new Map;function pk(t){let e=ny.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 ny.set(t,r),r}function gk(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 sy(){if(!ry)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return ry}async function oy(t,e={}){if(sn(t.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};if(!Sd(F.loadFromFile(V)))return{ok:!0,status:"skipped",reason:"observer_disabled"};let{sessionManager:r,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:o}=sy(),i=Y(t.platformSource),a=typeof t.cwd=="string"?t.cwd:"",c=a.trim()?await Mn(a):null,u=c?.primary||"unknown",l=F.loadFromFile(V);if(a&&Rn(a,l.MEMINDEX_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(Ft(t.toolName,l.MEMINDEX_SKIP_TOOLS)){if(t.toolName==="Skill"){let{skill_id:I,skill_source:y}=ZS(QS(t.toolName,t.toolInput));_d("skill_invoked",{skill_id:I,skill_source:y,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(i==="kimi"&&fk.has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let d=l.MEMINDEX_SKIP_BASH_PATTERNS.trim(),p=d?gk(t.toolName,t.toolInput):"";if(p){let I=pk(d);if(I&&I.test(p))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let g=Wr(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 I=t.toolInput,y=I.file_path||I.notebook_path;if(y&&y.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"};if(y&&th(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(I){let y=I instanceof Error?I.message:String(I);return f.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},I instanceof Error?I:new Error(y)),{ok:!1,reason:y,status:500}}if(!Xn.checkUserPromptPrivacy(h,t.contentSessionId,S,"observation",_,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let T=t.toolInput!==void 0?we(JSON.stringify(t.toolInput)):"{}",R=t.toolResponse!==void 0?we(JSON.stringify(t.toolResponse)):"{}";if(t.toolUseId)try{h.upsertToolUse({toolUseId:t.toolUseId,contentSessionId:t.contentSessionId,sessionDbId:_,project:u,platformSource:i,toolName:t.toolName,toolInput:T,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(I){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:_,toolName:t.toolName,toolUseId:t.toolUseId},I instanceof Error?I:new Error(String(I)))}return _a(t.toolName)?{ok:!0,status:"skipped",reason:"explicit_memory_write"}:(r.queueObservation(_,{tool_name:t.toolName,tool_input:T,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:_})}async function iy(t,e=sy(),r={}){let{sessionManager:n,dbManager:s,eventBroadcaster:o,ensureGeneratorRunning:i}=e,{contentSessionId:a,platformSource:c,observedModel:u,observedBilling:l}=t;if(t.agentId)return{status:"skipped",reason:"subagent_context"};let d=F.loadFromFile(V);if(!Sd(d))return{status:"skipped",reason:"observer_disabled"};if(ey(d))return{status:"skipped",reason:"summary_disabled"};let p=s.getSessionStore(),g=p.findSessionDbIdByContentSessionId(a,c);if(g===null)return{status:"unknown_session"};let h=(typeof t.cwd=="string"?t.cwd.trim():"")||p.getSessionCwd(g);if(h){let R=F.loadFromFile(V);if(Rn(h,R.MEMINDEX_EXCLUDED_PROJECTS))return{status:"skipped",reason:"project_excluded"}}if(u||l){p.setSessionObservedMetadata(g,u,l);let R=n.getSession(g);R&&(u&&(R.observedModel=u),l&&(R.observedBilling=l))}let _=p.getPromptNumberFromUserPrompts(a,g,t.enqueuedAtEpochMs);if(!Xn.checkUserPromptPrivacy(p,a,_,"summarize",g).allow)return{status:"skipped",reason:"private"};let w=t.lastAssistantMessage?we(String(t.lastAssistantMessage)):t.lastAssistantMessage,T=n.queueSummarize(g,w,_,t.enqueuedAtEpochMs);return r.markHandedOff?.(T),await i?.(g,"summarize"),o.broadcastSummarizeQueued(),{status:"accepted"}}var mk=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function hk(t){let e=typeof t.agentId=="string"?t.agentId.trim():"";return e&&e!=="*"?e:t.path.match(mk)?.[1]}var Ps=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}},ks=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}},xs=class extends Error{constructor(e,r){super(`summary not accepted for transcript session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptSummaryError",this.cause=r}},Sr=class extends Error{constructor(e,r){super(`transcript event not persisted for session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptSpoolError",this.cause=r}},_k=4096,Ek=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={},e.toolConsumptions=[]}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)Hn(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:Y(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>_k){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"||!Hn(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=Br(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=Br(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=Br(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 Mn(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){(i.sessions??=new Map).set(a,u.platformSource);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=jn(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=Jm(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-Ek))){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(`
45
- `):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 Zo({sessionId:e.sessionId,cwd:n,prompt:r,platform:e.platformSource})}catch(s){throw new Ps(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],s&&d&&d!==s&&p&&(s.toolConsumptions??=[]).push({owner:d,sessionKey:this.getSessionKey(r,e.sessionId),toolId:o,tool:p}))}}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:hk(r)};if(this.observationTransport==="spool"){try{qe("observation",o)}catch(a){throw new Sr(e.sessionId,a)}return}let i=!1;try{let a=await oy(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 ks(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 Km.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 Sr(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(`
46
- `);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{qe("summarize",{contentSessionId:e.sessionId,platformSource:e.platformSource,lastAssistantMessage:e.lastAssistantMessage??"",...e.cwd?{cwd:e.cwd}:{}})}catch(n){throw new Sr(e.sessionId,n)}return}let r=!1;try{await iy({contentSessionId:e.sessionId,lastAssistantMessage:e.lastAssistantMessage??"",platformSource:e.platformSource,...e.cwd?{cwd:e.cwd}:{}},void 0,{markHandedOff:()=>{r=!0}})}catch(n){if(r){f.warn("TRANSCRIPT","Summary accepted before generator kick failed",{sessionId:e.sessionId},n instanceof Error?n:void 0);return}throw new xs(e.sessionId,n)}}async updateContext(e,r){if(!r.context||r.context.mode!=="agents"||Tf(r)||!await Ln())return;let s=e.cwd??r.workspace;if(!s)return;let i=(await Mn(s)).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(i)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=ue(r.context.path??`${s}/AGENTS.md`),u=Os.default.resolve(c),l=[Os.default.resolve(s),Os.default.resolve(W)];if(!l.some(m=>u.startsWith(m+Os.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 be(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&&(Vm(c,g),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:r.name}))}};var ay=_e(require("node:zlib"),1),on=require("node:fs");M();function cy(){let t=ay.zstdDecompressSync;return typeof t=="function"?t:void 0}function uy(){return cy()!==void 0}var Sk=4247762216,yk=64*1024;function ya(t,e,r,n=Number.POSITIVE_INFINITY){let s=(0,on.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,yk),r-l),g=Buffer.alloc(p);if(o=g.subarray(0,(0,on.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)!==Sk)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,w=S===3?4:S,T=m===0?h?1:0:1<<m,R=(h?0:1)+w+T;if(u+R>r)return{frames:c,tornStart:l};for(u+=R;;){let I=a(u,3);if(!I)return{frames:c,tornStart:l};let y=I.readUIntLE(0,3);u+=3;let v=(y&1)!==0,A=y>>>1&3,b=y>>>3;if(A===3)throw new Error(`reserved Zstandard block type at byte ${u-3}`);let P=A===1?1:b;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,on.closeSync)(s)}}function yd(t,e){try{let r=cy();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 ly(t,e){return yd(t,e).toString("utf8")}var dy=2e3,bk=1e3,wk=2e3,Tk=256*1024,fy=4*1024*1024,Ik=16*1024*1024,vk=100,py=100;function Ns(){return new Promise(t=>setImmediate(t))}var ba=".jsonl.zstd";async function Rk(t,e){try{let r=0;for(;r<e;){let n=ya(t,r,e,Ik);if(n.tornStart!==null)return n.tornStart;if(n.frames.length===0)break;r=n.frames[n.frames.length-1].end,await Ns()}return r}catch{return e}}var gy=1024*1024;async function _y(t,e,r){let n;if(e){let{frames:o}=ya(t,0,Math.min(r,gy),1);if(o.length===0)return null;n=ly(await Ta(t,0,o[0].end),o[0])}else n=(await Ta(t,0,Math.min(r,gy))).toString("utf8");let s=n.indexOf(`
47
- `);return s<0?null:n.slice(0,s)}async function Ak(t,e,r){try{let n=await _y(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 wa(t){return`${t.dev}:${t.ino}`}function Mk(t){try{return(0,G.statSync)(t),!1}catch(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}}var Ok=4096;function wd(t,e,r){let n;try{if(n=(0,G.openSync)(t,"r"),wa((0,G.fstatSync)(n))!==r)return null;let s=Math.max(0,e-Ok),o=Buffer.alloc(e-s);return(0,G.readSync)(n,o,0,o.length,s)<o.length?null:(0,my.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,G.closeSync)(n)}}function Ey(t,e,r,n,s){return r<n?!1:s===void 0?!0:wd(t,n,e)===s}async function Ta(t,e,r){let n=await(0,hy.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 bd=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(ba),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;checkpointEachLine=!1;start(){this.requestRead();try{this.watcher=(0,G.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 Ns();while(this.readPending&&!this.closed)}async readNewData(){if(!(0,G.existsSync)(this.filePath))return;let e=0,r;try{let i=(0,G.statSync)(this.filePath);e=i.size,r=wa(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&&(Ey(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,s=!1){this.zstdPartialBytes=n,this.tailState.offset=e,this.tailState.partial=r,this.checkpointFingerprint=this.fileIdentity===void 0?void 0:wd(this.filePath,e,this.fileIdentity)??void 0,this.onOffset(e,r,this.frameLinesDone,this.fileIdentity,this.checkpointFingerprint,this.zstdPartialBytes?.toString("base64"),s)}async readNewJsonl(e){let r=this.tailState.readOffset,n;try{n=await Ta(this.filePath,r,Math.min(e-r,fy))}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%py===0?(this.checkpoint(this.tailState.offset),await Ns()):u&&this.checkpointEachLine&&this.checkpoint(this.tailState.offset,"",void 0,!0)}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=ya(this.filePath,r,e,fy),n.frames.length===0)return;let i=n.frames[n.frames.length-1].end;if(s=await Ta(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=yd(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%py===0&&await Ns()}}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)}},Ia=class{constructor(e,r,n="in-process",s){this.config=e;this.statePath=r;this.checkpointGate=s;this.processor=new Sa(n),this.state=Pf(r)}config;statePath;checkpointGate;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;heldCheckpoints=new Map;consumedToolCalls=new WeakSet;heldCheckpointTimer=null;missingTranscriptGraceMs=bk;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(),this.heldCheckpointTimer&&clearInterval(this.heldCheckpointTimer),this.heldCheckpointTimer=null,this.heldCheckpoints.clear()}commitHeldCheckpoints(){let e=this.checkpointGate;if(!e)return;let r=!1;try{for(let[n,s]of this.heldCheckpoints){let o=this.fileContexts.get(n)?.sessions??new Map,i=0,a=s.length-1,c=-1;for(;i<=a;){let u=i+a>>1;e.drainedThrough(o,s[u].sequence)?(c=u,i=u+1):a=u-1}if(!(c<0)){s[c].apply();for(let u=0;u<=c;u++)for(let l of s[u].consumeTools)l();s.splice(0,c+1),s.length===0&&this.heldCheckpoints.delete(n),r=!0}}}catch(n){f.warn("TRANSCRIPT","Could not check buffered work for held checkpoints",{},n instanceof Error?n:void 0)}r&&vr(this.statePath,this.state),this.heldCheckpoints.size===0&&this.heldCheckpointTimer&&(clearInterval(this.heldCheckpointTimer),this.heldCheckpointTimer=null)}holdCheckpoint(e,r,n,s){let o=this.checkpointGate.sequence(),i=this.heldCheckpoints.get(e)??[],a=i.at(-1);a?.sequence===o?(a.apply=r,a.consumeTools.push(...s)):i.push({sequence:o,apply:r,consumeTools:s}),this.heldCheckpoints.set(e,i),n&&this.commitHeldCheckpoints(),this.heldCheckpoints.size>0&&!this.heldCheckpointTimer&&(this.heldCheckpointTimer=setInterval(()=>this.commitHeldCheckpoints(),wk),this.heldCheckpointTimer.unref?.())}async setupWatch(e){let r=this.resolveSchema(e);if(!r){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=ue(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 Ns();o.stateChanged&&vr(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,G.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,G.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))},vk);this.rootWatchSettleTimers.add(a)}getFileContext(e){let r=this.fileContexts.get(e);if(!r){let n=this.state.pendingTools?.[e];r={cwd:this.state.cwds?.[e],pendingTools:n?Object.fromEntries(Object.entries(n).map(([s,o])=>[s,{...o}])):void 0,isCurrent:()=>this.isCheckpointedFile(e)},this.fileContexts.set(e,r)}return this.processor.registerFileContext(r),r}isCheckpointedFile(e){try{let r=(0,G.statSync)(e);return wa(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)||!Mk(n))continue;let s=this.fileContexts.get(n);s&&this.processor.retireFileContext(s),this.fileContexts.delete(n),this.heldCheckpoints.delete(n),this.state.pendingTools?.[n]&&(delete this.state.pendingTools[n],r=!0)}r&&vr(this.statePath,this.state)}forgetReplacedTranscript(e,r){this.heldCheckpoints.delete(e),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,G.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,G.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,G.existsSync)(e))try{return(0,G.statSync)(e).isDirectory()?[...this.scanGlob(this.normalizeGlobPattern((0,Q.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,Q.join)(e,"**",`*${ba}`)))]:[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=ue(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(ba);if(i&&!uy()){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,G.statSync)(e);if(s&&m.mtimeMs>=this.startedAtMs-dy&&await this.startedAfterThisWatcher(e,i,m.size)||(l=i?await Rk(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,G.statSync)(e),h=wa(m),_=this.state.fileIdentities?.[e],S=u!==void 0&&_!==void 0&&!Ey(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 w=wd(e,l,h);w!==null?(this.state.checkpointFingerprints??={})[e]=w: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?vr(this.statePath,this.state):o&&(o.stateChanged=!0));let p=l>0&&(!!n.sessionIdPath||!!r.subagentSource||!c.cwd),g=new bd(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.checkpointGate&&((this.state.pendingTools??={})[e]=c.pendingTools),c.cwd&&c.cwd!==this.state.cwds?.[e]&&((this.state.cwds??={})[e]=c.cwd)}},(m,h,_,S,w,T,R=!1)=>{let I=this.checkpointGate&&c.pendingTools?Object.fromEntries(Object.entries(c.pendingTools).map(([A,b])=>[A,{...b}])):void 0,y=(c.toolConsumptions?.splice(0)??[]).flatMap(({owner:A,sessionKey:b,toolId:P,tool:Ue})=>{let Ud=[...this.fileContexts].find(([,Ls])=>Ls===A)?.[0];return Ud?[()=>{this.consumedToolCalls.add(Ue);let Ls=this.state.pendingTools?.[Ud]?.[b];Ls?.[P]===Ue&&delete Ls[P]}]:[]}),v=()=>{if(I){for(let[A,b]of Object.entries(I)){for(let[P,Ue]of Object.entries(b))this.consumedToolCalls.has(Ue)&&delete b[P];Object.keys(b).length===0&&delete I[A]}(this.state.pendingTools??={})[e]=I}S!==void 0&&((this.state.fileIdentities??={})[e]=S),w!==void 0?(this.state.checkpointFingerprints??={})[e]=w: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],T?(this.state.partialBytes??={})[e]=T:this.state.partialBytes&&delete this.state.partialBytes[e],_>0?(this.state.frameLines??={})[e]=_:this.state.frameLines&&delete this.state.frameLines[e]};if(this.checkpointGate){this.holdCheckpoint(e,v,!R,y);return}v();for(let A of y)A();vr(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.checkpointEachLine=!!this.checkpointGate,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 Ak(e,r,n);return s!==null?s>=this.startedAtMs-dy:n<=Tk}async primeFromFirstLine(e,r,n,s,o,i){try{let a=await _y(e,e.endsWith(ba),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 Ps||a instanceof ks||a instanceof xs||a instanceof Sr)throw f.warn("TRANSCRIPT","Transcript event not accepted; it is retried from its own line",{watch:r.name,file:(0,Q.basename)(s),error:a.message}),a;a instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,Q.basename)(s)},a):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,Q.basename)(s),error:String(a)})}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};function Ld(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}function gb(t){(0,mb.existsSync)(ue(t))||(qa(t),console.log(`Created sample config: ${ue(t)}`))}async function hb(t,e){switch(t){case"init":{let r=Ld(e,"--config")??Ir;return qa(r),console.log(`Created sample config: ${ue(r)}`),0}case"watch":{let r=Ld(e,"--config")??Ir;gb(r);let n=F.loadFromFile(V),{config:s,scoped:o,removed:i}=If(Ya(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 ${ue(r)}; nothing to watch.`),1;let a=ue(s.stateFile??Ys),c=new Ia(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=Ld(e,"--config")??Ir;return gb(r),Ya(r),console.log(`Config OK: ${ue(r)}`),0}case"import":return z0(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 z0(t){let{defaultTranscriptImportDeps:e,formatTranscriptImportResult:r,isoOf:n,parseTranscriptImportArgs:s,runTranscriptImport:o,TRANSCRIPT_IMPORT_USAGE:i}=await Promise.resolve().then(()=>(pb(),fb)),{settleHookSpoolNudges:a}=await Promise.resolve().then(()=>($r(),Bm)),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],Y0=process.argv.slice(3);hb(V0,Y0).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});
40
+ ${e}`,i=Ym(s,o),a=`${t}.tmp`;try{(0,Je.writeFileSync)(a,i),(0,Je.renameSync)(a,t)}catch(c){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},c instanceof Error?c:new Error(String(c)))}}M();function xR(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 Wn(t,e){if(!e)return;let r=xR(e),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}function Jm(t){return t==null||t===""}function Zm(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 Br(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=Zm(t,r);return n!==void 0?n:Wn(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let n of t.coalesce){let s=Br(n,e,r);if(!Jm(s))return s}if(t.path){let n=Zm(t.path,r);if(n!==void 0)return n;let s=Wn(e,t.path);if(!Jm(s))return s}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function Qm(t,e,r){let n={};if(!t)return n;for(let[s,o]of Object.entries(t))n[s]=Br(o,e,r);return n}function Hn(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(!Hn(t,i,r))return!1}if(e.any!==void 0&&(!Array.isArray(e.any)||!e.any.some(i=>Hn(t,i,r))))return!1;let n=e.path||r.eventTypePath||"type",s=n?Wn(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}ut();$r();M();lt();Rn();ii();Bn();Ie();N();var ur=require("path");N();function CR(t=B.dataDir()){return(0,ur.join)(t,"bottles")}function nh(t,e){let r=(0,ur.resolve)(CR(e));return(0,ur.resolve)(t).startsWith(r+ur.sep)}nr();ut();M();var jn=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 Hr=require("path");function oh(){let t=DR();return async e=>{for(let r of e)r.module=t(r.filename);return e}}function DR(t=process.argv[1]?(0,Hr.dirname)(process.argv[1]):process.cwd(),e=Hr.sep==="\\"){let r=e?sh(t):t;return n=>{if(!n)return;let s=e?sh(n):n,{dir:o,base:i,ext:a}=Hr.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 sh(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var ee={};Ls(ee,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>wi,DOMExceptionCoercer:()=>Ku,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Qn,ErrorCoercer:()=>Yn,ErrorEventCoercer:()=>Gu,ErrorPropertiesBuilder:()=>Vn,EventCoercer:()=>zu,ExceptionStepsBuffer:()=>Ju,ObjectCoercer:()=>Jn,PrimitiveCoercer:()=>Zn,PromiseRejectionEventCoercer:()=>Vu,ReduceableCache:()=>Yu,StringCoercer:()=>qn,chromeStackLineParser:()=>Wu,createDefaultStackParser:()=>Xu,createStackParser:()=>Yh,geckoStackLineParser:()=>Hu,getInjectedReleaseId:()=>YA,getUtf8ByteLength:()=>Jh,nodeStackLineParser:()=>jh,opera10StackLineParser:()=>Bh,opera11StackLineParser:()=>Wh,resolveExceptionStepsConfig:()=>qu,reverseAndStripFrames:()=>Vh,stripReservedExceptionStepFields:()=>GA,winjsStackLineParser:()=>$h});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 Lt(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 FR=Array.isArray,ah=Object.prototype,wU=ah.hasOwnProperty,ai=ah.toString,Te=FR||function(t){return ai.call(t)==="[object Array]"};var Xn=t=>t===Object(t)&&!Te(t);var bt=t=>t===void 0,ce=t=>ai.call(t)=="[object String]",Mu=t=>ce(t)&&t.trim().length===0,Ou=t=>t===null,Ze=t=>bt(t)||Ou(t),jr=t=>ai.call(t)=="[object Number]"&&t===t;var ch=t=>ai.call(t)==="[object Boolean]";function ci(t){return t===null||typeof t!="object"}function lr(t,e){return Object.prototype.toString.call(t)===`[object ${e}]`}function Ut(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 dh(t,Error)}}function uh(t){return lr(t,"ErrorEvent")}function Xr(t){return"u">typeof Event&&dh(t,Event)}function lh(t){return lr(t,"Object")}function dh(t,e){try{return t instanceof e}catch{return!1}}var LR=["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"],ui=new Map,UR=256;function $R(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 fh=function(t,e=[]){if(!t)return!1;let r=$R(t,e),n=ui.get(r);if(n!==void 0)return n;let s=t.toLowerCase(),o=LR.concat(e).some(i=>s.indexOf(i.toLowerCase())!==-1);return ui.size>=UR&&ui.clear(),ui.set(r,o),o};function Kn(t,e,r,n,s){return e>r&&(n.warn("min cannot be greater than max."),e=r),jr(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),Kn(s??r,e,r,n))}var BR=864e5,WR=1,HR=10;function ph(t={}){return{refillRate:t.exceptionRateLimiterRefillRate??t.__exceptionRateLimiterRefillRate??WR,bucketSize:t.exceptionRateLimiterBucketSize??t.__exceptionRateLimiterBucketSize??HR}}var li=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Kn(e.bucketSize,0,100,e._logger),this._refillRate=Kn(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Kn(e.refillInterval,0,BR,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 di="0123456789abcdef",fi=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+=di.charAt(this.bytes[r]>>>4),e+=di.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+=di.charAt(this.bytes[r]>>>4),e+=di.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??jR()}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 fi.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,fi.ofInner(e)}},jR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),gh,fe=()=>XR().toString(),XR=()=>(gh||(gh=new Pu)).generate();var pi=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 KR(t=console){return{log:t.log.bind(t),warn:t.warn.bind(t),error:t.error.bind(t),debug:t.debug.bind(t)}}var mh=(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=>mh(`${t} ${o}`,e,r)}},GR=t=>t();function hh(t,e=GR){return mh(t,e,KR())}var Gr="Mobile",mi="iOS",Kr="Android",bh="Tablet",LU=Kr+" "+bh;var VR="Apple",UU=VR+" Watch",wh="Safari",hi="BlackBerry",Th="Samsung",YR=Th+"Browser",qR=Th+" Internet",_i="Chrome",JR=_i+" OS",ZR=_i+" "+mi,Ih="Internet Explorer",QR=Ih+" "+Gr,Nu="Opera",$U=Nu+" Mini",vh="Edge",eA="Microsoft "+vh,Cu="Firefox",tA=Cu+" "+mi,Du="Nintendo",Fu="PlayStation",gi="Xbox",rA=Kr+" "+Gr,nA=Gr+" "+wh,Gn="Windows",sA=Gn+" Phone";var Rh="Generic",BU=Rh+" "+Gr.toLowerCase(),WU=Rh+" "+bh.toLowerCase(),oA="Konqueror",iA="Oculus Browser",_h="Vivaldi",aA="Yandex",Eh="Whale",cA="DuckDuckGo",uA="Pale Moon",Sh="Waterfox",yh="Brave",Ah="Claude",Mh="Codex",Oh="ChatGPT",lA="Google Search App",X="(\\d+(\\.\\d+)?)",ku=new RegExp("Version/"+X),xu=new RegExp("("+Ah+"|"+Mh+"|"+Oh+")\\/"+X);var HU=new RegExp(gi,"i"),jU=new RegExp(Fu+" \\w+","i"),XU=new RegExp(Du+" \\w+","i"),dA=new RegExp(hi+"|PlayBook|BB10","i"),fA={"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 KU={[QR]:[new RegExp("rv:"+X)],[eA]:[new RegExp(vh+"?\\/"+X)],[_i]:[new RegExp("("+_i+"|CrMo)\\/"+X)],[ZR]:[new RegExp("CriOS\\/"+X)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+X)],[wh]:[ku],[nA]:[ku],[Nu]:[new RegExp("("+Nu+"|OPR)\\/"+X)],[Cu]:[new RegExp(Cu+"\\/"+X)],[tA]:[new RegExp("FxiOS\\/"+X)],[oA]:[new RegExp("Konqueror[:/]?"+X,"i")],[hi]:[new RegExp(hi+" "+X),ku],[rA]:[new RegExp("android\\s"+X,"i")],[qR]:[new RegExp(YR+"\\/"+X)],[iA]:[new RegExp("OculusBrowser\\/"+X)],[_h]:[new RegExp(_h+"\\/"+X)],[aA]:[new RegExp("YaBrowser\\/"+X)],[Eh]:[new RegExp(Eh+"\\/"+X)],[yh]:[new RegExp(yh+"\\/"+X)],[Ah]:[xu],[Mh]:[xu],[Oh]:[xu],[cA]:[new RegExp("(DuckDuckGo|Ddg)\\/"+X)],[uA]:[new RegExp("PaleMoon\\/"+X)],[Sh]:[new RegExp(Sh+"\\/"+X)],[lA]:[new RegExp("GSA\\/"+X)],[Ih]:[new RegExp("(rv:|MSIE )"+X)],Mozilla:[new RegExp("rv:"+X)]};var GU=[[new RegExp(gi+"; "+gi+" (.*?)[);]","i"),t=>[gi,t&&t[1]||""]],[new RegExp(Du,"i"),[Du,""]],[new RegExp(Fu,"i"),[Fu,""]],[dA,[hi,""]],[new RegExp(Gn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[sA,""];if(new RegExp(Gr).test(e)&&!/IEMobile\b/.test(e))return[Gn+" "+Gr,""];let r=/Windows NT ([0-9.]+)/i.exec(e);if(r&&r[1]){let n=r[1],s=fA[n]||"";return/arm/i.test(e)&&(s="RT"),[Gn,s]}return[Gn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){let e=[t[3],t[4],t[5]||"0"];return[mi,e.join(".")]}return[mi,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=bt(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Kr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Kr+")","i"),t=>{if(t&&t[2]){let e=[t[2],t[3],t[4]||"0"];return[Kr,e.join(".")]}return[Kr,""]}],[/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/,[JR,""]],[/Linux|debian/i,["Linux",""]]];var Ei="[Circular]",Si="[Truncated]",ke="[Unserializable]",Ph="[Function]",YU=Date.prototype.getTime,qU=Date.prototype.toISOString;function dt(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 wt(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=ke}Object.defineProperty(t,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return t}function Lu(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 dr=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 kh="utf8",pA=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gA(t){return typeof t=="string"&&pA.test(t)}function fr(t,e){return gA(t)?t:e()}function zr(t,e){let r=new Error(e);try{Object.defineProperty(r,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function xh(t){return t?.replace(/\/+$/,"")}async function Nh(t,e){let r=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await t()}catch(s){if(r=s,!e.retryCheck(s))throw s}}throw r}function Uu(){return new Date().toISOString()}function pe(t,e){let r=setTimeout(t,e);return r?.unref&&r?.unref(),r}async function $t(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 Ch=t=>t&&typeof t.then=="function";function zn(t){return Promise.all(t.map(e=>(e??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var $u,Dh,Fh,Vr;function Uh(t){let e=globalThis._posthogChunkIds,r=globalThis._debugIds;if(!e&&!r)return;let n=e?Object.keys(e):[],s=r?Object.keys(r):[];if(Vr&&Lh(e,n,Dh)&&Lh(r,s,Fh))return Vr;Dh=e?{...e}:void 0,Fh=r?{...r}:void 0,Vr={},$u??={};let o=(i,a)=>{for(let c of i){let u=a[c];if(!u)continue;let l=$u?.[c];if(l){Vr[l]=u;continue}let d=t(c);for(let p=d.length-1;p>=0;p--){let g=d[p]?.filename;if(g){Vr[g]=u,$u[c]=g;break}}}};return r&&o(s,r),e&&o(n,e),Vr}function Lh(t,e,r){return!t||!r?t===r:e.length===Object.keys(r).length&&e.every(n=>t[n]===r[n])}var Bu=50,mA=1e3,hA=100,_A=4,Vn=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&&Te(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:Uh(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(Ut(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&n<hA;n++){let s=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let o=e.errors;return Te(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=R=>{c.push(g);try{return S(R)}finally{c.pop()}},h>_A||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 v;try{if(v=this.applyCoercers(g,_),!v)throw u}catch(R){if(R===u){h===0&&s--;return}if(!i)throw R;v=this.coerceFallback(_)}if(!w||s>=Bu)return v;let I;try{I=w.length}catch{return v}if(!Number.isInteger(I)||I<0||I>4294967295)return v;let y=[];for(let R=0;s<Bu&&o<mA&&R<I;R++){o++;let A;try{A=_.next(w[R])}catch{s++,A=this.coerceFallback(d(m+1))}A&&y.push(A)}return{...v,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 se="?",EA="<anonymous>",SA=/^([a-z][a-z0-9.+-]+):/i,yA=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function bA(t){if(!t||t===EA)return!1;let e=SA.exec(t);return!e||yA.includes(e[1].toLowerCase())}function ft(t,e,r,n,s){let o={platform:t,filename:e,function:r==="<anonymous>"?se:r,in_app:bA(e)};return bt(n)||(o.lineno=n),bt(s)||(o.colno=s),o}var yi=(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]:se,r?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};var wA=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,TA=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,IA=/\((\S*)(?::(\d+))(?::(\d+))\)/,Wu=(t,e)=>{let r=wA.exec(t);if(r){let[,s,o,i]=r;return ft(e,s,se,+o,+i)}let n=TA.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=IA.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,i]=yi(n[1]||se,n[2]);return ft(e,i,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var vA=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,RA=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Hu=(t,e)=>{let r=vA.exec(t);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let i=RA.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]||se;return[o,s]=yi(o,s),ft(e,s,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var AA=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,$h=(t,e)=>{let r=AA.exec(t);return r?ft(e,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var MA=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Bh=(t,e)=>{let r=MA.exec(t);return r?ft(e,r[2],r[3]||se,+r[1]):void 0},OA=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Wh=(t,e)=>{let r=OA.exec(t);return r?ft(e,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var PA=/^\s*[-]{4,}$/,kA=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,xA=/^Promise\.(?:all|any)$/,NA=/^index \d+$/,CA="node:internal/promise",jh=(t,e)=>{let r=t.match(kA);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||se,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]),xA.test(o)&&NA.test(c||"")&&(c=CA),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:Hh(r[3]),colno:Hh(r[4]),in_app:DA(c||"",u),platform:e}}if(t.match(PA))return{filename:t,platform:e}};function DA(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 Hh(t){return parseInt(t||"",10)||void 0}var Xh=/\(error: (.*)\)/,Kh=50,FA=10,LA=1e3;function ju(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function UA(t){for(let e=1;e<=FA;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(!ju(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 $A(t,e){let r=e.start+e.length,n=zh(t,e);n&&t.splice(r+n===t.length?r:e.start,n)}function Gh(t,e){let r=e.start;for(;r>0&&ju(t[r-1],t[r-1+e.length]);)r--;return e.start-r}function zh(t,e){let r=e.start+e.length,n=r;for(;n<t.length&&ju(t[n],t[n-e.length]);)n++;return n-r}function BA(t,e){let r=e[0],n=t.length-(r?Gh(t,r):0);for(let s of e)n-=zh(t,s);return n}function WA(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++)HA(e,n,r)&&(r=n);t.push(...t.splice(0,r))}function HA(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 Vh(t){if(!t.length)return[];let e=Array.from(t);return e.reverse(),e.slice(0,Kh).map(r=>({...r,filename:r.filename||jA(e).filename,function:r.function||se}))}function jA(t){return t[t.length-1]||{}}function Xu(){return Yh("web:javascript",Wu,Hu)}function Yh(t,...e){return(r,n=0)=>{let s=[],o=r.split(`
41
+ `),i=Math.min(o.length,n+LA),a=[];for(let l=n;l<i;l++){let d=o[l];if(d.length>1024)continue;let p=Xh.test(d)?d.replace(Xh,"$1"):d;if(!p.match(/\S*Error: /)){for(let g of e){let m=g(p,t);if(m){s.push(m);let h=UA(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(BA(s,a)>=Kh)break}}let c=[...a].sort((l,d)=>d.start-l.start),u=c[c.length-1];if(u){let l=Gh(s,u);s.splice(u.start-l,l);for(let d of c)d.start-=l}for(let l of c)$A(s,l);return a.some(l=>l.start===0&&s.length===l.length)&&WA(s),Vh(s)}}var Ku=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,r){let n=ce(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 lr(e,"DOMException")}isDOMError(e){return lr(e,"DOMError")}};var Yn=class{match(e){return Ut(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 Gu=class{match(e){if(!uh(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 ce(e.message)&&e.message.length>0}_buildLocationStack(e){let r=e,n=r.lineno??0,s=r.colno??0;if(!(!ce(r.filename)||r.filename.length===0)&&n!==0)return`Error
42
+ at ${r.filename}:${n}:${s}`}};var XA=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,qn=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(XA);return s&&(r=s[1],n=s[2]),[r,n]}};var qh=["fatal","error","warning","log","info","debug"];function bi(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 Jn=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(Xr(e))return e.constructor.name;let r="name"in e?e.name:void 0;return ce(r)&&!Mu(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=bi(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return ce(e)&&!Mu(e)&&qh.indexOf(e)>=0}getStack(e){try{return ce(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ce(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(Ut(n))return n}}getObjectClassName(e){try{let r=Object.getPrototypeOf(e);return r?r.constructor.name:void 0}catch{return}}};var zu=class{match(e){return Xr(e)}coerce(e,r){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${bi(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Zn=class{match(e){return ci(e)}coerce(e,r){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Vu=class{match(e){return lr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xr(e))return!1;try{let r=e.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(e,r){let n=this.getUnhandledRejectionReason(e);return ci(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var Yu=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let r=this._cache.get(e);if(r!==void 0)return this._cache.delete(e),this._cache.set(e,r),r}set(e,r){this._cache.set(e,r)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var Qn={MESSAGE:"$message",TIMESTAMP:"$timestamp"},KA=new Set([Qn.MESSAGE,Qn.TIMESTAMP]),wi={enabled:!0,max_bytes:32768};function qu(t){return t?{enabled:t.enabled??wi.enabled,max_bytes:zA(t.max_bytes,wi.max_bytes)}:{...wi}}function GA(t){if(!t)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(t).reduce((n,s)=>KA.has(s)?(e.push(s),n):(n[s]=t[s],n),{}),droppedKeys:e}}var Ju=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=qu(e)}setConfig(e){this._config=qu(e),this._trimToMaxBytes()}add(e){let r=VA(e);if(!r)return;let n=Jh(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 zA(t,e){if(!jr(t)||t===1/0||t===-1/0)return e;let r=Math.floor(t);return r<0?e:r}function VA(t){let e;try{e=Lt(t)}catch{return}try{let r=JSON.parse(e);if(!Xn(r))return;let n=r,s=n[Qn.MESSAGE],o=n[Qn.TIMESTAMP];return!ce(s)||s.trim().length===0||!ce(o)&&!jr(o)?void 0:{step:n,json:e}}catch{return}}function Jh(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 YA(){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 Zu=t=>{if("flags"in t){let e=Zh(t.flags),r=Qh(t.flags);return{...t,featureFlags:e,featureFlagPayloads:r}}{let e=t.featureFlags??{},r=Object.fromEntries(Object.entries(t.featureFlagPayloads||{}).map(([s,o])=>[s,Yr(o)])),n=Object.fromEntries(Object.entries(e).map(([s,o])=>[s,qA(s,o,r[s])]));return{...t,featureFlags:e,featureFlagPayloads:r,flags:n}}};function qA(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 Zh=t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,es(r)]).filter(([,e])=>e!==void 0)),Qh=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?Yr(n):void 0]}))},es=t=>t===void 0?void 0:t.variant??t.enabled,Yr=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};var e_=["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"],JA=["$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",...e_,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],ts=(t,e=[])=>{let r={},n=s=>{t[s]!==void 0&&(r[s]=t[s])};return JA.forEach(n),e.forEach(n),r};var Ti=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 Qu(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var QA="NativeGzipValidationError",eM=31,tM=139,rM=8,nM=t=>t.length>=2&&t[0]===eM&&t[1]===tM;var rs,sM=()=>{if(rs)return rs;rs=[];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;rs[t]=e>>>0}return rs},oM=t=>{let e=sM(),r=4294967295;for(let n=0;n<t.length;n++)r=e[(r^t[n])&255]^r>>>8;return(4294967295^r)>>>0},Ii=t=>{throw zr(QA,`Native gzip produced invalid output: ${t}`)},iM=async(t,e)=>{t.size<18&&Ii("too-short");let r=new Uint8Array(await t.slice(0,10).arrayBuffer());(!nM(r)||r[2]!==rM)&&Ii("invalid-header");let n=new DataView(await t.slice(t.size-8).arrayBuffer());n.getUint32(0,!0)!==oM(e)&&Ii("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&Ii("invalid-size")};async function ns(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 iM(c,n),c}catch(n){if(r?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var xe=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 Lu(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=zr("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=zr("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{}})()}},Tt=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var aM=(t,e)=>{for(let r of Object.keys(e))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(t[r]=e[r])};async function t_(t){if(t instanceof xe){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 cM(t){return typeof t=="object"&&(t instanceof xe||o_(t))}function o_(t){return t instanceof Tt}function uM(t){if(t instanceof xe)return t.status===502||t.status===504;if(!(t instanceof Tt))return!1;let e=t.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var r_=10485760;function n_(t){try{return typeof t!="string"?t instanceof Uint8Array?t.byteLength:t.size:"u">typeof Buffer?Buffer.byteLength(t,kh):new TextEncoder().encode(t).length}catch{return 0}}function qr(t){return typeof t=="object"&&t instanceof xe&&t.status===413}function vi(t){return t instanceof xe?t.status===408||t.status===429||t.status>=500:o_(t)}function s_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var el="default",ss=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Vn([new Yn,new Jn,new qn,new Zn],Xu())}getEvaluationRuntime(){}constructor(e,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new pi,this._events=new Ti,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=hh("[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=xh(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:vi},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=!Qu()||(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 aM(n,r),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=ts(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:uM},this.featureFlagsRequestTimeoutMs).then(p=>({success:!0,response:Zu(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(e){if(e instanceof xe)return{type:"api_error",statusCode:e.status};if(e instanceof Tt){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=es(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 el}persistedQueueKeyForRoute(e){return he.Queue}getActiveQueueRoutes(){return[el]}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=s_(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=fr(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:Uu(),uuid:fr(r?.uuid,fe)};return(r?.disableGeoip??this.disableGeoip)&&(s_(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 t_(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(()=>zn([r])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),zn([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 ns(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,r,n=el){let s={api_key:this.apiKey,batch:e.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:Uu()};this.historicalMigration&&(s.historical_migration=!0);let o=Lt(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=>qr(d)?!1:vi(d)};try{await this.sendBatch(c,l,e)}catch(d){if(qr(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 Tt||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=n_(s);if(o>r_)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${o} bytes: the endpoint accepts at most ${r_}`)),{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=>qr(l)||l instanceof xe&&l.retryAfterMs!==void 0?!1:vi(l)}),{kind:"ok"}}catch(l){if(qr(l))return{kind:"too-large"};if(vi(l)){let d=l instanceof xe?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=n_(i),c={...this._retryOptions,...s},u=0;return await Nh(async()=>{u++;let l=new AbortController,d=o??this.requestTimeout,p=Date.now()+d,g,m=new Promise((w,v)=>{g=pe(()=>{let I=zr("AbortError",`Request timed out after ${d}ms`);v(I),l.abort(I)},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 Tt(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 Tt(y)}let v=r.mode==="no-cors",I=n.type==="successful-write"?300:400;if(!v&&(h.status<200||h.status>=I))throw new xe(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 Tt(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 xe&&l.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:$t((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(!cM(s))throw s;await t_(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 gM=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var rW=new RegExp(gM.source,"i"),i_=/[a-z][a-z0-9+.-]{0,63}:\/\//i,nW=new RegExp(`^${i_.source}`,"i"),sW=new RegExp(i_.source,"gi");var mM=["is_not","is_set"],hM=1152921504606847e3,O=class t extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,t.prototype)}};function tl(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(!tl(e in t?t[e]:null))return!1;return!0}function rl(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(!rl(e in t?t[e]:null))return!1;return!0}function os(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 O("Cannot stringify an unpaired surrogate like the flags service");e++}else if(r>=56320&&r<=57343)throw new O("Cannot stringify an unpaired surrogate like the flags service")}}function Ai(t,e=new Set){if(!(t===null||typeof t=="boolean")){if(typeof t=="string")return void os(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new O(`Cannot represent non-finite number ${t} like the flags service`);return}if(Array.isArray(t)){if(e.has(t))throw new O("Cannot represent a circular array during local evaluation");e.add(t);try{for(let r=0;r<t.length;r++)r in t&&Ai(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 O("Cannot represent a non-JSON object like the flags service");if(e.has(t))throw new O("Cannot represent a circular object during local evaluation");e.add(t);try{for(let n of Object.keys(t))os(n),Ai(t[n],e)}finally{e.delete(t)}return}throw new O(`Cannot represent ${typeof t} like the flags service`)}}function _M(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 nl(t,e=new Set){if(t===null)return"null";if(typeof t=="string")return os(t),JSON.stringify(t);if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new O(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new O(`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 O("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?nl(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 O("Cannot stringify a non-JSON object like the flags service");if(e.has(t))throw new O("Cannot stringify a circular object during local evaluation");e.add(t);try{let n=Object.keys(t);return n.forEach(os),`{${n.sort(_M).map(s=>`${JSON.stringify(s)}:${nl(t[s],e)}`).join(",")}}`}finally{e.delete(t)}}throw new O(`Cannot stringify ${typeof t} like the flags service`)}function Ri(t){return typeof t=="string"?(os(t),t):nl(t)}function a_(t){try{return new RegExp(t),!0}catch{return!1}}function Ne(t){return String(t).replace(/[A-Z]/g,e=>e.toLowerCase())}function u_(t,e,r){if(!/^\d+$/.test(t)||r==="strict"&&t.length>1&&t[0]==="0")throw new O(`Invalid semver: ${e}`);return parseInt(t,10)}function Z(t,e="strict"){let n=String(t).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new O(`Invalid semver: ${t}`);let s=n.split("."),o=i=>i===void 0||i===""?0:u_(i,t,e);return[o(s[0]),o(s[1]),o(s[2])]}function Ce(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 EM(t,e){let r=Z(t,e);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function SM(t,e){let[r,n,s]=Z(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 yM(t,e){let n=String(t).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new O(`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 u_(c,t,e)}catch{}throw new O(`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 c_(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 O(`${t} is in an invalid date format`)}throw new O(`The date provided ${t} must be a string, number, or date object`)}function sl(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 ol(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 O(`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&&!mM.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&&tl(d)||Array.isArray(d)&&d.length===0)return Ai(p),rl(d)===rl(p);if(r.propertyMatchingVersion===2&&typeof p=="number"&&tl(d))return Ai(p),!1;if(Array.isArray(d)){let g=Ri(p).toLowerCase();return d.some(m=>Ri(m).toLowerCase()===g)}return Ri(d).toLowerCase()===Ri(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 Ne(c).includes(Ne(s));case"not_icontains":return!Ne(c).includes(Ne(s));case"starts_with":return Ne(c).startsWith(Ne(s));case"not_starts_with":return!Ne(c).startsWith(Ne(s));case"ends_with":return Ne(c).endsWith(Ne(s));case"not_ends_with":return!Ne(c).endsWith(Ne(s));case"regex":return a_(String(s))&&String(c).match(String(s))!==null;case"not_regex":return a_(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 O("Date operations cannot be performed on boolean values");let d=sl(String(s));d==null&&(d=c_(s));let p=c_(c);return o==="is_date_before"?p<d:p>d}case"semver_eq":return Ce(Z(String(c),i),Z(String(s),i))===0;case"semver_neq":return Ce(Z(String(c),i),Z(String(s),i))!==0;case"semver_gt":return Ce(Z(String(c),i),Z(String(s),i))>0;case"semver_gte":return Ce(Z(String(c),i),Z(String(s),i))>=0;case"semver_lt":return Ce(Z(String(c),i),Z(String(s),i))<0;case"semver_lte":return Ce(Z(String(c),i),Z(String(s),i))<=0;case"semver_tilde":{let d=Z(String(c),i),{lower:p,upper:g}=EM(String(s),i);return Ce(d,p)>=0&&Ce(d,g)<0}case"semver_caret":{let d=Z(String(c),i),{lower:p,upper:g}=SM(String(s),i);return Ce(d,p)>=0&&Ce(d,g)<0}case"semver_wildcard":{let d=Z(String(c),i),{lower:p,upper:g}=yM(String(s),i);return Ce(d,p)>=0&&Ce(d,g)<0}default:throw new O(`Unknown operator: ${o}`)}}async function l_(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 is(t,e,r="",n="."){let s=await l_(`${t}${n}${e}${r}`);return parseInt(s.slice(0,15),16)/hM}async function il(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 is("holdout",e,"","-")>n/100))return`holdout-${t.id}`}function Mi(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 al(t,e,r){let n=await is(t,e,"variant");return Mi(r).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function cl(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:Yr(n)}var d_=9223372036854776e3,bM="9223372036854775808",wM=Object.prototype.propertyIsEnumerable;function TM(){return{ancestors:new WeakSet,remainingNodes:1e4}}function pt(t,e){try{return f_(t,e,TM(),0)}catch{return[]}}function IM(t,e){let r=t.toString(),n=BigInt(bM);return t>=n||t<-n?(e?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function dl(t,e,r,n){if(r.remainingNodes<=0)return{stringValue:Si};if(r.remainingNodes--,ch(t))return{boolValue:t};if(typeof t=="bigint")return IM(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>=d_||t<-d_?(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:dt(t)};if(typeof t=="function")return{stringValue:Ph};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(r.ancestors.has(t))return{stringValue:Ei};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"?dt(o):String(o)}}r.ancestors.add(t);try{try{let s=t.toJSON;if(typeof s=="function")return dl(s.call(t),e,r,n+1)}catch{}return Te(t)?{arrayValue:{values:vM(t,e,r,n+1)}}:{kvlistValue:{values:f_(t,e,r,n+1)}}}finally{r.ancestors.delete(t)}}return{stringValue:dt(String(t))}}function vM(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(Ze(a))continue;s.push(dl(a,e,r,n))}catch{s.push({stringValue:ke})}return t.length>i&&s.push({stringValue:Si}),s}function f_(t,e,r,n){let s=[];for(let o in t)if(wM.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(Ou(i)||bt(i))continue;s.push({key:dt(o),value:dl(i,e,r,n)})}catch{s.push({key:dt(o),value:{stringValue:ke}})}}return s}function cs(t,e,r){return{...wt({},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 RM=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function us(t,e){let r=wt({},t),n={};for(let s of RM)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s],delete r[s]);return[...pt(r,e),...pt(n,e)]}var p_={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 AM(t){if(t)return Object.prototype.hasOwnProperty.call(p_,t)?p_[t]:t}function fl(t,e){let r=AM(t);return{...r?{"os.name":r}:{},...e?{"os.version":e}:{}}}var MM={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}},yW=MM.info;var pr=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 ls(){return 1-.25+Math.random()*.25*2}var De=1;function ds(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 pl="0000000000000000",xM=pl+pl,NM=/^[0-9a-f]+$/;function CM(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 DM(t){let e="";for(let r=0;r<t.length;r++)e+=t[r].toString(16).padStart(2,"0");return e}function g_(t){let e=DM(CM(t));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function m_(){return g_(16)}function h_(){return g_(8)}function __(t,e,r){return typeof t=="string"&&t.length===e&&t!==r&&NM.test(t)}function E_(t){return __(t,32,xM)}function S_(t){return __(t,16,pl)}var FM=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Pi(t){let e=y_(t);return e&&{traceId:e.traceId,spanId:e.spanId,flags:LM(e.flags)}}function LM(t){return 1&parseInt(t,16)?Jr:UM}function y_(t){if(typeof t!="string")return;let e=FM.exec(t.trim());if(!e)return;let[,r,n,s,o,i]=e;if(r!=="ff"&&!(r==="00"&&i)&&!(!E_(n)||!S_(s)))return{version:r,traceId:n,spanId:s,flags:o}}function b_(t){return y_(t)&&t.trim()}function ki(t){return Array.isArray(t)&&t.length===1?t[0]:t}var Jr="01",UM="00";function w_(t,e,r=Jr){return`00-${t}-${e}-${r}`}var $M=32,gl=512;function xi(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>$M)){for(let n of r)if(n.trim()&&!n.includes("="))return;return e.length<=gl?e:WM(r)}}var BM=128;function WM(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()>gl;n--)e[n].length>BM&&e.splice(n,1);for(;e.length&&r()>gl;)e.pop();return e.length?e.join(","):void 0}var fs=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ni(t){return String(t)+"000000"}function ml(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 T_(t,e){for(let r=0;r<e.length;r++)if(t<=e[r])return r;return e.length}function hl(t,e,r){return cs(t,e,r)}function _l(t,e,r,n){return{resourceMetrics:[{resource:{attributes:us(e)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]}}function Ci(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 I_=1,ps=class{constructor(e,r,n){this._instance=e,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new pr(()=>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 dr,this._consecutiveFlushFailures=0,this._flushJitter=De,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=De,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=ml(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=Pi(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Jr)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(fs.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[T_(r,fs)]+=1;break}}}_runBeforeSend(e){let r=this._config.beforeSend;if(!r)return e;let n=Te(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(ds(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=ls()):(this._consecutiveFlushFailures=0,this._flushJitter=De),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 _l(this._buildMetrics(e),hl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let r=Ni(Date.now()),n=new Map;for(let s of e.values()){let o=ml(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:I_,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?i.gauge={dataPoints:[]}:i.histogram={aggregationTemporality:I_,dataPoints:[]},n.set(o,i));let a=pt(s.attributes??{},this._logger),c=Ni(s.windowStartMs),u=HM(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:fs,...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 HM(t){return t?{exemplars:[{filteredAttributes:[],timeUnixNano:Ni(t.timeMs),asDouble:t.value,traceId:t.traceId,spanId:t.spanId}]}:{}}var v_="unknown";function gr(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 "${v_}"`),v_)}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 R_(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 Di(t,e){return t<e?e:t}function gs(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 Li(){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??Jr,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:Li(),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=Li();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(Ze(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]=$i(r,this._maxAttributeValueLength)}setAttribute(e,r){return this._mutable("setAttribute")&&this._writeAttribute(e,r),this}setAttributes(e){if(this._mutable("setAttributes")){let r=wt({},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&&P_(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:gr(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:gs(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:El(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}=Sl(e);return this.addEvent(jM,{"exception.type":r,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=gr(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return w_(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=gs(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:Di(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},jM="exception",XM=4294967295;function KM(t){try{return typeof t=="string"?t:String(t)}catch{return ke}}function mr(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:Math.min(Math.floor(t),XM)}function GM(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 M_(t,e,r,n,s,o,i=[]){let a=0,c=0,u={};for(let g of GM(t.attributes,i)){let m=t.attributes[g];if(!Ze(m)){if(!e.has(g)){if(a>=r){c++;continue}a++}Object.defineProperty(u,g,{value:$i(m,o),enumerable:!0,writable:!0,configurable:!0})}}t.attributes=u,c&&(t.droppedAttributesCount=mr(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=P_(g.attributes,s,o);g.attributes=m.attributes,m.dropped&&(g.droppedAttributesCount=mr(g.droppedAttributesCount)+m.dropped)}p.push(g)}t.events=p,d&&(t.droppedEventsCount=mr(t.droppedEventsCount)+d),t.status?.message&&(t.status={...t.status,message:El(KM(t.status.message),o)})}var Ui=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(){}},O_=new Ui,ms=class extends Ui{constructor(e,r){super(),this._traceparent=e,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function zM(t){try{let e=t.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Bt(t,e){let r=ki(t?.parent)??e,n=typeof r=="string"||r==null?r:A_(r,"traceparent"),s=b_(n);if(!s)return O_;let o=typeof r=="string"||r==null?t?.tracestate:A_(r,"tracestate");return new ms(s,xi(o))}function A_(t,e){try{let r=t[e];return typeof r=="function"?r.call(t):void 0}catch{return}}function El(t,e){return t.length>e?t.slice(0,e):t}function $i(t,e){return Fi(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Fi(t,e,r,n){if(t===null||typeof t!="object")return Ze(t)||r.remainingNodes<=0?t:(r.remainingNodes--,typeof t=="string"?El(t,e):t);if(r.ancestors.has(t))return Ei;if(r.remainingNodes<=0||n>=20)return t;r.remainingNodes--,r.ancestors.add(t);try{if(t instanceof Date)return t;let s=VM(t);if(s.selfDescribed)return Ze(s.value)?String(s.value):Fi(s.value,e,r,n+1);if(Te(t)){let a=Math.min(t.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(Fi(t[u],e,r,n+1))}catch{c.push(ke)}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=Fi(t[a],e,r,n+1)}catch{c=ke}a&&!Ze(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 VM(t){try{let e=t.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(t)}}catch{}return{selfDescribed:!1}}function P_(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=$i(t[a],r)}catch{c=ke}Ze(c)||(o++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:i}}function k_(t,e){for(let r of Object.keys(t))t[r]=$i(t[r],e);return t}function hs(t,e,r){return e===O_?r(e):t.with(e,()=>r(e))}function Sl(t){try{let e=zM(t);if(Ut(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 yl={internal:1,server:2,client:3,producer:4,consumer:5},YM={ok:1,error:2},qM=1,JM=256,ZM=512;function QM(t){let e=parseInt(t.traceFlags,16);return(Number.isFinite(e)?255&e:qM)|JM|(t.parentIsRemote?ZM:0)}function Bi(t){if(typeof t=="string")return dt(t);try{return dt(String(t))}catch{return ke}}function eO(t){return t&&Object.prototype.hasOwnProperty.call(yl,t)?yl[t]:yl.internal}function bl(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 tO(t,e){let r={name:Bi(t.name),timeUnixNano:bl(t.timestamp)};if(t.attributes){let s=pt(t.attributes,e);s.length&&(r.attributes=s)}let n=mr(t.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function x_(t,e){let r={traceId:t.traceId,spanId:t.spanId,name:Bi(t.name),kind:eO(t.kind),startTimeUnixNano:bl(t.startTime),endTimeUnixNano:bl(t.endTime),flags:QM(t)};t.parentSpanId&&(r.parentSpanId=t.parentSpanId),t.traceState&&(r.traceState=Bi(t.traceState));let n=pt(t.attributes,e);n.length&&(r.attributes=n),t.events.length&&(r.events=t.events.map(i=>tO(i,e)));let s=mr(t.droppedAttributesCount);s&&(r.droppedAttributesCount=s);let o=mr(t.droppedEventsCount);return o&&(r.droppedEventsCount=o),t.status&&(r.status={code:YM[t.status.code],...t.status.message&&{message:Bi(t.status.message)}}),r}function N_(t,e,r){return cs(t,e,r)}function C_(t,e,r,n,s){return{resourceSpans:[{resource:{attributes:us(e,s)},scopeSpans:[{scope:{name:r,version:n},spans:t}]}]}}var D_=8;function Wi(){return Li()??Date.now()}function wl(t){try{return t instanceof Qr}catch{return!1}}function F_(t,e){let r=Pi(t);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:xi(e),traceFlags:r.flags,isRemote:!0}}function rO(t){try{return typeof t.traceparent=="function"}catch{return!1}}function nO(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 Hi(t,e,r){t[e]!==r&&(t[e]=r)}function sO(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 _s=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 pr(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=De,this._retryAfter=new dr,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 Bt(r,this._contextManager.active());let n=ki(r?.parent);if(n&&typeof n!="string"&&!wl(n)){if(rO(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Bt(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`),Bt(r,this._contextManager.active());let o=Date.now(),i=R_(r?.startTime,o,this._logger),a=h_();this._liveSpans.set(a,Wi());let c=this._autoContextAttributes();return new Qr({traceId:s?.traceId??m_(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:gr(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:wt({...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=hs(this._contextManager,i,o);return Ch(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=De,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,r){if(typeof e=="string"){let s=F_(e,r?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(wl(e))return e.childContext();let n=this._contextManager.active();if(wl(n))return n.childContext();if(n instanceof ms)return F_(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}=Sl(r);e.addEvent("exception",{"exception.type":n,"exception.message":s,...o&&{"exception.stacktrace":o}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=Wi()-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},!nO(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=gr(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=Di(Zr(l.endTime)??s.endTime,l.startTime);let p=[];for(let g of l.events)try{p.push({...g,name:gr(g.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:gs(g.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=p,M_(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{Hi(e,"traceId",r.traceId),Hi(e,"spanId",r.spanId),Hi(e,"parentSpanId",r.parentSpanId),Hi(e,"traceState",r.traceState)}catch{return sO(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(x_(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=k_(N_(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=Wi()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(C_(g,r,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=De,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=De,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=ls(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=Wi()+this._nextFlushDelay()),this._headBatchFailures<D_)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=De,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${D_} 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=De,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(ds(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var Es=class{active(){return this._active}with(e,r){let n=this._active;this._active=e;try{return r()}finally{this._active=n}}};var oO=5e3,iO=512,aO=2048,cO=128,uO=128,lO=128,dO=8192,fO=1e4,pO=36e5;function Wt(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:e}var L_=["service.name","service.version","deployment.environment"];function gO(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{if(L_.every(r=>!(r in t)||typeof t[r]=="string"))return t;let e={...t};for(let r of L_)r in e&&typeof e[r]!="string"&&delete e[r];return e}catch{return}}function mO(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 Tl(t,e,r){let n=wt({...e},gO(t?.resourceAttributes)),s=Wt(t?.maxExportBatchSize,iO);return{serviceName:n?.["service.name"]??t?.serviceName,serviceVersion:n?.["service.version"]??t?.serviceVersion,environment:n?.["deployment.environment"]??t?.environment,resourceAttributes:n,beforeSpanSend:mO(t?.beforeSpanSend,r),maxAttributesPerSpan:Wt(t?.maxAttributesPerSpan,cO),maxEventsPerSpan:Wt(t?.maxEventsPerSpan,uO),maxAttributesPerEvent:lO,maxAttributeValueLength:Wt(t?.maxAttributeValueLength,dO),flushIntervalMs:Wt(t?.flushIntervalMs,oO),maxExportBatchSize:s,maxQueueSize:Math.max(Wt(t?.maxQueueSize,aO),s),maxLiveSpans:Wt(t?.maxLiveSpans,fO),maxSpanAgeMs:Wt(t?.maxSpanAgeMs,pO)}}var Il=require("node:fs"),B_=require("node:fs/promises"),Rl=require("node:path"),W_=require("node:readline"),ji=new ee.ReduceableCache(25),Ss=new ee.ReduceableCache(20),Al=7,hO=1e3,_O=1e4,vl=10485760;async function H_(t,e=B_.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"||wO(u)||TO(c)||!(0,Rl.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=j_(a,s);if(c===void 0||Ss.get(c))continue;let u=n[a];if(!u)continue;u.sort((p,g)=>p-g);let l=vO(u);if(l.every(p=>IO(c,p)))continue;let d=RO(ji,c,{});i.push(SO(a,l,d,c,e,r))}return await Promise.all(i).catch(()=>{}),t&&t.length>0&&yO(t,ji,s),ji.reduce(),t}async function EO(t,e,r){let n,s=!1;try{n=await e(t,Il.constants.O_RDONLY|Il.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>vl?void r?.debug(`Skipping source context for oversized file ${t}: ${o.size} bytes exceeds ${vl}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function SO(t,e,r,n,s,o){let i=await EO(t,s,o);if(i===void 0)return void Ss.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:vl-1})}catch{Ss.set(n,1),l();return}let p;try{p=(0,W_.createInterface)({input:d})}catch{Ss.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(){Ss.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]=AO(w,0),g>=S)){if(m===e.length-1){p.close(),p.removeAllListeners();return}m++;let v=e[m];if(v===void 0){p.close(),p.removeAllListeners();return}_=v[0],S=v[1]}})})}function yO(t,e,r){for(let n of t)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=j_(n.filename,r),o=s===void 0?void 0:e.get(s);if(o===void 0)continue;bO(n.lineno,n,o)}}function bO(t,e,r){if(e.lineno===void 0||r===void 0)return;e.pre_context=[];for(let s=X_(t);s<t;s++){let o=r[s];if(o===void 0)return void U_(e);e.pre_context.push(o)}if(r[t]===void 0)return void U_(e);e.context_line=r[t];let n=K_(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 U_(t){delete t.pre_context,delete t.context_line,delete t.post_context}function wO(t){return t.startsWith("node:")||t.endsWith(".min.js")||t.endsWith(".min.cjs")||t.endsWith(".min.mjs")||t.startsWith("data:")}function TO(t){return t.lineno!==void 0&&t.lineno>_O||t.colno!==void 0&&t.colno>hO}function j_(t,e){return(0,Rl.isAbsolute)(t)?JSON.stringify([null,t]):e===void 0?void 0:JSON.stringify([e,t])}function IO(t,e){let r=ji.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 vO(t){if(!t.length)return[];let e=0,r=t[0];if(typeof r!="number")return[];let n=$_(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+Al:(s.push(n),n=$_(o)),e++}return s}function $_(t){return[X_(t),K_(t)]}function X_(t){return Math.max(1,t-Al)}function K_(t){return t+Al}function RO(t,e,r){let n=t.get(e);return n===void 0?(t.set(e,r),r):n}function AO(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 en=require("path");function G_(t=process.cwd()){let e=en.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,en.isAbsolute)(o.filename)&&(o.filename=r((0,en.relative)(n,r(o.filename))));return s}}var z_="5.56.2";var It={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Ht=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(It.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(It.QUOTA_LIMITED),r===void 0&&o.push(It.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 V_(t){return t==="client"||t==="server"?t:"all"}function OO(t,e){return t===e||t==="all"||e==="all"}var hr=class t extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t.prototype)}};function PO(t,e){t.name=e.name,Error.captureStackTrace(t,e),Object.setPrototypeOf(t,e.prototype)}var gt=class t extends Error{constructor(e){super(e),PO(this,t)}},Xi=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 gt||u instanceof O?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 gt||u instanceof O?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=cl(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 O("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 O("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 O(`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 O("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new O(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let i=e.dependency_chain;if(!Array.isArray(i))throw new O(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof i})`);if(i.length===0)throw new O(`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 O(`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 O(`Missing flag dependency '${c}' for flag '${o}'`)}if(s[c]==null)throw new O(`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 il(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,v=o.multivariate?.variants||[];g=w&&v.some(I=>I.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 gt)throw h;if(h instanceof O)p=!0;else throw h}if(g!==void 0)return g;if(p)throw new O("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 q_(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):Y_(u,s,c,i.propertyMatchingVersion);if(!d)return"no_match"}if(a==null)return"match"}return a!=null&&await is(e.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,r){return al(e.key,r,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return Mi(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?V_(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(r=>OO(V_(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 hr(`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 hr(`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 hr(`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 hr&&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 hr("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 $t(r,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Y_(t,e,r,n){return ol(t,e,{warnFunction:r,propertyMatchingVersion:n})}function kO(t,e){if(!(t in e))throw new gt(`cohort ${t} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function q_(t,e,r,n=!1,s,o){let i=String(t.value);kO(i,r);let a=r[i];return J_(a,e,r,n,s,o)}async function J_(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 J_(u,e,r,n,s,o);if(i==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof gt)throw l;if(l instanceof O)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new O("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 q_(u,e,r,n,s,o);else if(u.type==="flag"){if(!s)throw new O(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await s(u)}else l=Y_(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 gt)throw l;if(l instanceof O)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new O("can't match cohort without a given cohort property value");return i==="AND"}var xO=["--unhandled-rejections","--unhandled_rejections"],NO=new Set(["throw","strict","warn","warn-with-error-code","none"]),CO=[...globalThis.process?.execArgv??[]],DO=globalThis.process?.env?.NODE_OPTIONS;function FO(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 Z_(t){let e;for(let r=0;r<t.length;r++){let n=t[r],s=xO.find(i=>n===i||n.startsWith(`${i}=`));if(!s)continue;let o=n===s?t[++r]:n.slice(s.length+1);NO.has(o)&&(e=o)}return e}function LO(t=CO,e=DO){return Z_(t)??Z_(FO(e??""))??"throw"}var Q_=LO();function eE(t,e,r){t(e,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function UO(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;eE(t,n,s),!r&&o===0&&(r=!0,e(n))},{_posthogErrorHandler:!0})}function tE(t,e,r=Q_){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(s,o)=>eE(t,s,o));n.on("uncaughtException",UO(t,e))}}function rE(t,e=Q_){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 $O=2e3,Ml=class t{constructor(e,r,n){this.client=e,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new li({...ph(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Xn(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()&&(tE(this.onException.bind(this),this.onFatalError.bind(this)),rE(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($O),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},_r=Ml;var EP=/^[0-9a-f]{32}$/i,SP=/^[0-9a-f]{16}$/i,yP;async function FS(){try{let e=(await(yP??=Promise.resolve().then(()=>(DS(),CS)))).trace.getActiveSpan()?.spanContext(),r=e?.traceId,n=e?.spanId;if(typeof r=="string"&&typeof n=="string"&&EP.test(r)&&SP.test(n)&&!/^0+$/.test(r)&&!/^0+$/.test(n))return{$trace_id:r.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var ia=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,r){this._memoryStorage[e]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function bP(t){return t==="v0"||t==="v1"}function LS(){let t="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return bP(t)?t:"v0"}var wP="$ai_",Rs="analytics";function US(t){return typeof t.event=="string"&&t.event.startsWith(wP)}var nn=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 pd(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 TP(t){return typeof t=="string"?t:void 0}var IP=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:pd},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:pd},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:pd},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:TP}],vP=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function RP(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function AP(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 $S(t,e,r){r!==void 0&&!(e in t)&&(t[e]=r)}function MP(t){let r={...RP(t.properties)?t.properties:{}},n={};for(let{property:o,optionKey:i,coerce:a}of IP)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 vP)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,$S(r,"$set",t.$set),$S(r,"$set_once",t.$set_once),{event:String(t.event??""),uuid:String(t.uuid??""),distinct_id:String(t.distinct_id??""),timestamp:AP(t.timestamp),...s,options:n,properties:r}}function BS(t,{createdAt:e,historicalMigration:r}){let n={created_at:e,batch:t.map(MP)};return r&&(n.historical_migration=!0),n}var OP="/i/v1/analytics/events",PP=3e4,kP=new Set([408,500,502,503,504]),aa=class{constructor(e,r){this.config=e,this.maxBackoffMs=e.maxBackoffMs??PP,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??ns}async sendV1Batch(e){if(e.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=BS(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${OP}`,i=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,d=Lt({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&&kP.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(v){if(h.aborted)throw v;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 nn({requestId:r,drops:i,retryExhausted:b.map(v=>v.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 nn({requestId:e,drops:r,retryExhausted:n.map(o=>o.uuid),cause:s}))}surfacePartialDrops(e,r){r.length>0&&this.onError(new nn({requestId:e,drops:r,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var Er="ai-capture",ca="/i/v0/ai/batch/";var NP=new TextEncoder;function md(t){return NP.encode(Lt(t)).length}function WS(t,e=8388608,r=5242880){let n=[],s=[],o=[],i=0;for(let a of t){if(a===void 0)continue;let c=md(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 CP=100,HS=3e4,DP=5e4,FP=50,LP=500,UP="https://us.i.posthog.com",jS=new Set;function la(t,e){jS.has(t)||(jS.add(t),console.warn(`[PostHog] ${e}`))}function $P(t){return typeof t=="string"?t.trim():""}function BP(t){return(typeof t=="string"?t.trim():"")||void 0}function WP(t){return(typeof t=="string"?t.trim():"")||UP}function HP(t){return(Array.isArray(t)?t:[t]).filter(r=>typeof r=="string"&&r.trim().length>0)}function jP(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 da=class extends ss{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,r={}){let n=$P(e),s={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:WP(r.host),personalApiKey:BP(r.secretKey??r.personalApiKey)};if(super(n,s),this._memoryStorage=new ia,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=LS(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,CP):s.featureFlagsPollingInterval===null?null:HS,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 Xi({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 _r(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||DP}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:zn([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??LP,s=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??FP;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"&&US(e)?"ai":Rs}persistedQueueKeyForRoute(e){return e===Er?he.AiCaptureQueue:e==="ai"?he.AiQueue:he.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[Rs,"ai"]:[Rs];return this._aiCaptureRouteActive&&e.push(Er),e}getBatchEndpointPath(e){return e===Er?ca:super.getBatchEndpointPath(e)}async sendBatch(e,r,n=Rs){if(n===Er)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}=WS(e);for(let{event:o,bytes:i}of s){let a=`Event ${o} (${i} bytes) exceeds the ${8388608/1048576}MiB limit for ${ca}, 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,Er)}catch(n){if(!qr(n))throw n;if(e.length===1){let[o]=e,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${md(o)} bytes) was rejected with 413 by ${ca} 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 aa({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 z_}get metrics(){return this._metrics||(this._metrics=new ps(this,Ci(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new Es}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 _s(this,Tl(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)??Bt(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):hs(this._spanContextManager,Bt(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=fr(e.uuid,fe);return this._sendPreparedAiEvent({...e,uuid:r},!1),r}async captureAiImmediate(e){if(this.disabled)return;let r=fr(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,Er)}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=HP(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=HS){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 R=this._flagOverrides[e];if(R===void 0)return;let A=this._payloadOverrides?.[e];return{key:e,enabled:R!==!1,variant:typeof R=="string"?R: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,v,I;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let R=this.featureFlagsPoller?.featureFlagsByKey[e];if(R)try{let A=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(R,p,{matchValue:s});if(A){m=!0;let T=A.value;b=R.id,v="Evaluated locally",I=R.has_experiment,g={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:A.payload??void 0,reason:v,reasonCode:R.active===!1?"flag_disabled":void 0}}}catch(A){if(A instanceof gt||A instanceof O)this._logger?.info(`${A.name} when computing flag locally: ${e}: ${A.message}`);else throw A}}if(!m&&!c){let R=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,a,[e]);if(R===void 0)S=It.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,h=R.requestId,_=R.evaluatedAt;let A=[];R.errorsWhileComputingFlags&&A.push(It.ERRORS_WHILE_COMPUTING),R.quotaLimited?.includes("feature_flags")&&A.push(It.QUOTA_LIMITED);let T=R.flags[e];if(T===void 0)A.push(It.FLAG_MISSING);else{b=T.metadata?.id,w=T.metadata?.version,v=T.reason?.description??T.reason?.code,I=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:v,reasonCode:T.reason?.code}}A.length>0&&(S=A.join(","))}}if(o){let R=g===void 0?void 0:g.enabled===!1?!1:g.variant??!0,A={$feature_flag:e,$feature_flag_response:R,$feature_flag_id:b,$feature_flag_version:w,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${e}`]:R,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():_};if(I!==void 0&&(A.$feature_flag_has_experiment=I),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:R,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){la("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(la("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){la("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 Ht({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Ht({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:i}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new Ht({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),v=new Set;if(w)for(let[R,A]of Object.entries(w.response)){let T=this.featureFlagsPoller?.featureFlagsByKey[R];m[R]={key:R,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:w.payloads[R],id:T?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:T?.has_experiment},v.add(R)}let I=g!==void 0&&Array.from(g).some(R=>this.featureFlagsPoller?.featureFlagsByKey[R]===void 0);if((w?w.fallbackToFlags||I:!0)&&!c){let R=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,i,a);if(R){this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,h=R.requestId,_=R.evaluatedAt,S=!!R.errorsWhileComputingFlags,b=Array.isArray(R.quotaLimited)&&R.quotaLimited.includes("feature_flags");for(let[A,T]of Object.entries(R.flags)){if(v.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[R,A]of Object.entries(this._flagOverrides)){if(A===void 0){delete m[R];continue}let T=m[R];m[R]={key:R,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[R,A]of Object.entries(this._payloadOverrides)){let T=m[R];T&&(m[R]={...T,payload:A})}if(g!==void 0)for(let R of Object.keys(m))g.has(R)||delete m[R];return new Ht({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 $t(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await $t(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(lh(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(!_r.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");this.addPendingPromise(_r.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(!_r.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(_r.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 FS()),m||(m=fe(),h.$process_person_profile=!1),g&&p?.sessionId&&!h.$session_id&&(h.$session_id=p.sessionId);let _=this._shouldSendMinimalFlagCalledEvent(s,h)?ts(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){la("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,v=await this.getFeatureFlagsForEvent(S.distinctId,i,l,w);return jP(v)}return{}}).catch(()=>({})).then(w=>{let v=S.groups||i;return{...w,...S.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});return S.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"&&fh(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 XS=require("node:async_hooks"),fa=class{constructor(){this.storage=new XS.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 KS=require("node:async_hooks"),pa=class{active(){return this._storage.getStore()}with(e,r){return this._storage.run(e,r)}constructor(){this._storage=new KS.AsyncLocalStorage}};var GS=require("node:zlib"),zS=require("node:util"),XP=(0,zS.promisify)(GS.gzip);async function VS(t,e=!0){try{let r=await XP(t);return new Uint8Array(r)}catch(r){return e&&console.error("Failed to gzip compress data",r),null}}var ga=require("node:os");function YS(){let t,e;try{t=(0,ga.platform)(),e=(0,ga.release)()}catch{}return fl(t,e)}var qS="posthog-node";function KP(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[hd.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 hd=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,r,n,s,o){this.name=qS,this.name=qS,this.setupOnce=function(i,a){let c=a()?.getClient()?.getDsn()?.projectId;i(KP(e,{organization:r,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:o??!0}))}}};var ma=class extends da{getLibraryId(){return"posthog-node"}compressPayload(e){return VS(e,this.isDebug)}initializeContext(){return new fa}initializeSpanContextManager(){return new pa}hostResourceAttributes(){return YS()}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),[oh(),e=>H_(e,void 0,this._logger),G_()])}};bc();Rc();vc();Mc();var RG=300*1e3,AG=3600*1e3;M();var Ed=null,GP=!1,zP=3e4,ha=null;function ZS(){let t=Date.now();if(ha&&t<ha.expiresAt)return ha.value;let e=go(process.env,yn());return ha={value:e,expiresAt:t+zP},e}var VP=!1;function YP(){if(!Ed){let t=VP&&mp(process.env)&&ZS();Ed=new ma(_o(),{host:Eo(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:t,before_send:sk})}return Ed}var qP=6e4,JP=500,As=new Map;function ZP(t,e,r){let n="";try{let s=(r||"").split(`
43
+ `).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}::${bp(e)}::${n}`.slice(0,400)}function QP(t,e){try{return ek(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 ek(t,e){let r=As.get(t);if(!r){if(As.size>=JP){let n=null,s=1/0;for(let[o,i]of As){let a=Math.max(i.lastSentTs,i.firstTs);a<s&&(s=a,n=o)}n!==null&&As.delete(n)}return r={count:1,firstTs:e,lastSentTs:e},As.set(t,r),{send:!0,count:1}}if(r.count+=1,e-r.lastSentTs>=qP){r.lastSentTs=e;let n=r.count;return r.count=0,{send:!0,count:n}}return{send:!1,count:r.count}}var JS="__cm_rate_limited";function tk(t){try{return typeof t!="string"||t.length===0?"":Tc(wc(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 rk(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=yp(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=tk(a.filename))}}}function nk(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 sk(t){try{if(!t||typeof t!="object")return t;let e=t;if(e.event!=="$exception")return t;let r=e.properties??{};if(nk(r))return null;if(r[JS]){try{delete r[JS],e.properties=r}catch{}return t}rk(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=ZP(n,s,o),a=QP(i,Date.now());if(!a.send)return null;try{r.occurrence_count=a.count,e.properties=r}catch{}return t}catch{return null}}function _d(t,e,r){try{ok(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 ok(t,e,r){if(GP||!ZS())return;let n=ho({...yo(),...e??{}});if(r?.person?n.$set=So(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
44
+ `);return}YP().capture({distinctId:mo(),event:t,properties:n})}var ik=["cloud-sync","distill","handoff","how-it-works","import-chats","import-jira","import-reviews","knowledge-agent","mem-search","mode-creator","pin","savings","timeline-report","weekly-digests"],ak=new Set(ik),QS={skill_id:"other",skill_source:"third_party"};function ey(t){let e=ck(t);return e&&ak.has(e)?{skill_id:e,skill_source:"first_party"}:QS}function ty(t,e){if(t==="Skill"&&!(!e||typeof e!="object"))return e.skill}function ck(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}M();ut();function uk(t){return["false","0","off","no"].includes(String(t??"").trim().toLowerCase())}function lk(t){return["true","1","on","yes"].includes(String(t??"").trim().toLowerCase())}function Sd(t){return!uk(t.MEMINDEX_OBSERVER_ENABLED)}function ry(t){return lk(t.MEMINDEX_DISABLE_SUMMARY)}Ea();var sy=null,fk=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),oy=new Map;function pk(t){let e=oy.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 oy.set(t,r),r}function gk(t,e){if(!e||typeof e!="object")return"";let r=e,n=t==="exec_command"?r.cmd:t==="run_command"?r.CommandLine:t==="Bash"||t==="PowerShell"?r.command:void 0;return typeof n=="string"?n:""}function iy(){if(!sy)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return sy}async function ay(t,e={}){if(sn(t.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};if(!Sd(F.loadFromFile(V)))return{ok:!0,status:"skipped",reason:"observer_disabled"};let{sessionManager:r,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:o}=iy(),i=Y(t.platformSource),a=typeof t.cwd=="string"?t.cwd:"",c=a.trim()?await An(a):null,u=c?.primary||"unknown",l=F.loadFromFile(V);if(a&&vn(a,l.MEMINDEX_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(Ft(t.toolName,l.MEMINDEX_SKIP_TOOLS)){if(t.toolName==="Skill"){let{skill_id:I,skill_source:y}=ey(ty(t.toolName,t.toolInput));_d("skill_invoked",{skill_id:I,skill_source:y,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(i==="kimi"&&fk.has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let d=l.MEMINDEX_SKIP_BASH_PATTERNS.trim(),p=d?gk(t.toolName,t.toolInput):"";if(p){let I=pk(d);if(I&&I.test(p))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let g=Wr(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 I=t.toolInput,y=I.file_path||I.notebook_path;if(y&&y.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"};if(y&&nh(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(I){let y=I instanceof Error?I.message:String(I);return f.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},I instanceof Error?I:new Error(y)),{ok:!1,reason:y,status:500}}if(!jn.checkUserPromptPrivacy(h,t.contentSessionId,S,"observation",_,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let w=t.toolInput!==void 0?we(JSON.stringify(t.toolInput)):"{}",v=t.toolResponse!==void 0?we(JSON.stringify(t.toolResponse)):"{}";if(t.toolUseId)try{h.upsertToolUse({toolUseId:t.toolUseId,contentSessionId:t.contentSessionId,sessionDbId:_,project:u,platformSource:i,toolName:t.toolName,toolInput:w,toolResponse:v,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(I){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:_,toolName:t.toolName,toolUseId:t.toolUseId},I instanceof Error?I:new Error(String(I)))}return _a(t.toolName)?{ok:!0,status:"skipped",reason:"explicit_memory_write"}:(r.queueObservation(_,{tool_name:t.toolName,tool_input:w,tool_response:v,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:_})}async function cy(t,e=iy(),r={}){let{sessionManager:n,dbManager:s,eventBroadcaster:o,ensureGeneratorRunning:i}=e,{contentSessionId:a,platformSource:c,observedModel:u,observedBilling:l}=t;if(t.agentId)return{status:"skipped",reason:"subagent_context"};let d=F.loadFromFile(V);if(!Sd(d))return{status:"skipped",reason:"observer_disabled"};if(ry(d))return{status:"skipped",reason:"summary_disabled"};let p=s.getSessionStore(),g=p.findSessionDbIdByContentSessionId(a,c);if(g===null)return{status:"unknown_session"};let h=(typeof t.cwd=="string"?t.cwd.trim():"")||p.getSessionCwd(g);if(h){let v=F.loadFromFile(V);if(vn(h,v.MEMINDEX_EXCLUDED_PROJECTS))return{status:"skipped",reason:"project_excluded"}}if(u||l){p.setSessionObservedMetadata(g,u,l);let v=n.getSession(g);v&&(u&&(v.observedModel=u),l&&(v.observedBilling=l))}let _=p.getPromptNumberFromUserPrompts(a,g,t.enqueuedAtEpochMs);if(!jn.checkUserPromptPrivacy(p,a,_,"summarize",g).allow)return{status:"skipped",reason:"private"};let b=t.lastAssistantMessage?we(String(t.lastAssistantMessage)):t.lastAssistantMessage,w=n.queueSummarize(g,b,_,t.enqueuedAtEpochMs);return r.markHandedOff?.(w),await i?.(g,"summarize"),o.broadcastSummarizeQueued(),{status:"accepted"}}var mk=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function hk(t){let e=typeof t.agentId=="string"?t.agentId.trim():"";return e&&e!=="*"?e:t.path.match(mk)?.[1]}var Os=class extends Error{constructor(e,r){super(`session init failed for transcript session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptAnchorError",this.cause=r}},Ps=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}},ks=class extends Error{constructor(e,r){super(`summary not accepted for transcript session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptSummaryError",this.cause=r}},Sr=class extends Error{constructor(e,r){super(`transcript event not persisted for session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptSpoolError",this.cause=r}},_k=4096,Ek=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={},e.toolConsumptions=[]}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)Hn(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:Y(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>_k){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"||!Hn(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=Br(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=Br(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=Br(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 An(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){(i.sessions??=new Map).set(a,u.platformSource);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=Wn(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=Qm(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-Ek))){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(`
45
+ `):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 Zo({sessionId:e.sessionId,cwd:n,prompt:r,platform:e.platformSource})}catch(s){throw new Os(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],s&&d&&d!==s&&p&&(s.toolConsumptions??=[]).push({owner:d,sessionKey:this.getSessionKey(r,e.sessionId),toolId:o,tool:p}))}}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:hk(r)};if(this.observationTransport==="spool"){try{qe("observation",o)}catch(a){throw new Sr(e.sessionId,a)}return}let i=!1;try{let a=await ay(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 Ps(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 zm.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 Sr(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(`
46
+ `);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{qe("summarize",{contentSessionId:e.sessionId,platformSource:e.platformSource,lastAssistantMessage:e.lastAssistantMessage??"",...e.cwd?{cwd:e.cwd}:{}})}catch(n){throw new Sr(e.sessionId,n)}return}let r=!1;try{await cy({contentSessionId:e.sessionId,lastAssistantMessage:e.lastAssistantMessage??"",platformSource:e.platformSource,...e.cwd?{cwd:e.cwd}:{}},void 0,{markHandedOff:()=>{r=!0}})}catch(n){if(r){f.warn("TRANSCRIPT","Summary accepted before generator kick failed",{sessionId:e.sessionId},n instanceof Error?n:void 0);return}throw new ks(e.sessionId,n)}}async updateContext(e,r){if(!r.context||r.context.mode!=="agents"||vf(r)||!await Fn())return;let s=e.cwd??r.workspace;if(!s)return;let i=(await An(s)).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(i)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=ue(r.context.path??`${s}/AGENTS.md`),u=Ms.default.resolve(c),l=[Ms.default.resolve(s),Ms.default.resolve(W)];if(!l.some(m=>u.startsWith(m+Ms.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 be(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&&(qm(c,g),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:r.name}))}};var uy=_e(require("node:zlib"),1),on=require("node:fs");M();function ly(){let t=uy.zstdDecompressSync;return typeof t=="function"?t:void 0}function dy(){return ly()!==void 0}var Sk=4247762216,yk=64*1024;function ya(t,e,r,n=Number.POSITIVE_INFINITY){let s=(0,on.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,yk),r-l),g=Buffer.alloc(p);if(o=g.subarray(0,(0,on.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)!==Sk)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,v=(h?0:1)+b+w;if(u+v>r)return{frames:c,tornStart:l};for(u+=v;;){let I=a(u,3);if(!I)return{frames:c,tornStart:l};let y=I.readUIntLE(0,3);u+=3;let R=(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,R)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,on.closeSync)(s)}}function yd(t,e){try{let r=ly();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 fy(t,e){return yd(t,e).toString("utf8")}var py=2e3,bk=1e3,wk=2e3,Tk=256*1024,gy=4*1024*1024,Ik=16*1024*1024,vk=100,my=100;function xs(){return new Promise(t=>setImmediate(t))}var ba=".jsonl.zstd";async function Rk(t,e){try{let r=0;for(;r<e;){let n=ya(t,r,e,Ik);if(n.tornStart!==null)return n.tornStart;if(n.frames.length===0)break;r=n.frames[n.frames.length-1].end,await xs()}return r}catch{return e}}var hy=1024*1024;async function Sy(t,e,r){let n;if(e){let{frames:o}=ya(t,0,Math.min(r,hy),1);if(o.length===0)return null;n=fy(await Ta(t,0,o[0].end),o[0])}else n=(await Ta(t,0,Math.min(r,hy))).toString("utf8");let s=n.indexOf(`
47
+ `);return s<0?null:n.slice(0,s)}async function Ak(t,e,r){try{let n=await Sy(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 wa(t){return`${t.dev}:${t.ino}`}function Mk(t){try{return(0,G.statSync)(t),!1}catch(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}}var Ok=4096;function wd(t,e,r){let n;try{if(n=(0,G.openSync)(t,"r"),wa((0,G.fstatSync)(n))!==r)return null;let s=Math.max(0,e-Ok),o=Buffer.alloc(e-s);return(0,G.readSync)(n,o,0,o.length,s)<o.length?null:(0,_y.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,G.closeSync)(n)}}function yy(t,e,r,n,s){return r<n?!1:s===void 0?!0:wd(t,n,e)===s}async function Ta(t,e,r){let n=await(0,Ey.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 bd=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(ba),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;checkpointEachLine=!1;start(){this.requestRead();try{this.watcher=(0,G.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 xs();while(this.readPending&&!this.closed)}async readNewData(){if(!(0,G.existsSync)(this.filePath))return;let e=0,r;try{let i=(0,G.statSync)(this.filePath);e=i.size,r=wa(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&&(yy(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,s=!1){this.zstdPartialBytes=n,this.tailState.offset=e,this.tailState.partial=r,this.checkpointFingerprint=this.fileIdentity===void 0?void 0:wd(this.filePath,e,this.fileIdentity)??void 0,this.onOffset(e,r,this.frameLinesDone,this.fileIdentity,this.checkpointFingerprint,this.zstdPartialBytes?.toString("base64"),s)}async readNewJsonl(e){let r=this.tailState.readOffset,n;try{n=await Ta(this.filePath,r,Math.min(e-r,gy))}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%my===0?(this.checkpoint(this.tailState.offset),await xs()):u&&this.checkpointEachLine&&this.checkpoint(this.tailState.offset,"",void 0,!0)}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=ya(this.filePath,r,e,gy),n.frames.length===0)return;let i=n.frames[n.frames.length-1].end;if(s=await Ta(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=yd(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%my===0&&await xs()}}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)}},Ia=class{constructor(e,r,n="in-process",s){this.config=e;this.statePath=r;this.checkpointGate=s;this.processor=new Sa(n),this.state=xf(r)}config;statePath;checkpointGate;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;heldCheckpoints=new Map;consumedToolCalls=new WeakSet;heldCheckpointTimer=null;missingTranscriptGraceMs=bk;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(),this.heldCheckpointTimer&&clearInterval(this.heldCheckpointTimer),this.heldCheckpointTimer=null,this.heldCheckpoints.clear()}commitHeldCheckpoints(){let e=this.checkpointGate;if(!e)return;let r=!1;try{for(let[n,s]of this.heldCheckpoints){let o=this.fileContexts.get(n)?.sessions??new Map,i=0,a=s.length-1,c=-1;for(;i<=a;){let u=i+a>>1;e.drainedThrough(o,s[u].sequence)?(c=u,i=u+1):a=u-1}if(!(c<0)){s[c].apply();for(let u=0;u<=c;u++)for(let l of s[u].consumeTools)l();s.splice(0,c+1),s.length===0&&this.heldCheckpoints.delete(n),r=!0}}}catch(n){f.warn("TRANSCRIPT","Could not check buffered work for held checkpoints",{},n instanceof Error?n:void 0)}r&&vr(this.statePath,this.state),this.heldCheckpoints.size===0&&this.heldCheckpointTimer&&(clearInterval(this.heldCheckpointTimer),this.heldCheckpointTimer=null)}holdCheckpoint(e,r,n,s){let o=this.checkpointGate.sequence(),i=this.heldCheckpoints.get(e)??[],a=i.at(-1);a?.sequence===o?(a.apply=r,a.consumeTools.push(...s)):i.push({sequence:o,apply:r,consumeTools:s}),this.heldCheckpoints.set(e,i),n&&this.commitHeldCheckpoints(),this.heldCheckpoints.size>0&&!this.heldCheckpointTimer&&(this.heldCheckpointTimer=setInterval(()=>this.commitHeldCheckpoints(),wk),this.heldCheckpointTimer.unref?.())}async setupWatch(e){let r=this.resolveSchema(e);if(!r){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=ue(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 xs();o.stateChanged&&vr(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,G.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,G.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))},vk);this.rootWatchSettleTimers.add(a)}getFileContext(e){let r=this.fileContexts.get(e);if(!r){let n=this.state.pendingTools?.[e];r={cwd:this.state.cwds?.[e],pendingTools:n?Object.fromEntries(Object.entries(n).map(([s,o])=>[s,{...o}])):void 0,isCurrent:()=>this.isCheckpointedFile(e)},this.fileContexts.set(e,r)}return this.processor.registerFileContext(r),r}isCheckpointedFile(e){try{let r=(0,G.statSync)(e);return wa(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)||!Mk(n))continue;let s=this.fileContexts.get(n);s&&this.processor.retireFileContext(s),this.fileContexts.delete(n),this.heldCheckpoints.delete(n),this.state.pendingTools?.[n]&&(delete this.state.pendingTools[n],r=!0)}r&&vr(this.statePath,this.state)}forgetReplacedTranscript(e,r){this.heldCheckpoints.delete(e),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,G.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,G.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,G.existsSync)(e))try{return(0,G.statSync)(e).isDirectory()?[...this.scanGlob(this.normalizeGlobPattern((0,Q.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,Q.join)(e,"**",`*${ba}`)))]:[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=ue(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(ba);if(i&&!dy()){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,G.statSync)(e);if(s&&m.mtimeMs>=this.startedAtMs-py&&await this.startedAfterThisWatcher(e,i,m.size)||(l=i?await Rk(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,G.statSync)(e),h=wa(m),_=this.state.fileIdentities?.[e],S=u!==void 0&&_!==void 0&&!yy(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=wd(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?vr(this.statePath,this.state):o&&(o.stateChanged=!0));let p=l>0&&(!!n.sessionIdPath||!!r.subagentSource||!c.cwd),g=new bd(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.checkpointGate&&((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,v=!1)=>{let I=this.checkpointGate&&c.pendingTools?Object.fromEntries(Object.entries(c.pendingTools).map(([A,T])=>[A,{...T}])):void 0,y=(c.toolConsumptions?.splice(0)??[]).flatMap(({owner:A,sessionKey:T,toolId:P,tool:Ue})=>{let Ud=[...this.fileContexts].find(([,Fs])=>Fs===A)?.[0];return Ud?[()=>{this.consumedToolCalls.add(Ue);let Fs=this.state.pendingTools?.[Ud]?.[T];Fs?.[P]===Ue&&delete Fs[P]}]:[]}),R=()=>{if(I){for(let[A,T]of Object.entries(I)){for(let[P,Ue]of Object.entries(T))this.consumedToolCalls.has(Ue)&&delete T[P];Object.keys(T).length===0&&delete I[A]}(this.state.pendingTools??={})[e]=I}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]};if(this.checkpointGate){this.holdCheckpoint(e,R,!v,y);return}R();for(let A of y)A();vr(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.checkpointEachLine=!!this.checkpointGate,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 Ak(e,r,n);return s!==null?s>=this.startedAtMs-py:n<=Tk}async primeFromFirstLine(e,r,n,s,o,i){try{let a=await Sy(e,e.endsWith(ba),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 Os||a instanceof Ps||a instanceof ks||a instanceof Sr)throw f.warn("TRANSCRIPT","Transcript event not accepted; it is retried from its own line",{watch:r.name,file:(0,Q.basename)(s),error:a.message}),a;a instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,Q.basename)(s)},a):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,Q.basename)(s),error:String(a)})}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};function Ld(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}function hb(t){(0,_b.existsSync)(ue(t))||(qa(t),console.log(`Created sample config: ${ue(t)}`))}async function Eb(t,e){switch(t){case"init":{let r=Ld(e,"--config")??Ir;return qa(r),console.log(`Created sample config: ${ue(r)}`),0}case"watch":{let r=Ld(e,"--config")??Ir;hb(r);let n=F.loadFromFile(V),{config:s,scoped:o,removed:i}=Rf(Ya(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 ${ue(r)}; nothing to watch.`),1;let a=ue(s.stateFile??Ys),c=new Ia(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=Ld(e,"--config")??Ir;return hb(r),Ya(r),console.log(`Config OK: ${ue(r)}`),0}case"import":return z0(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 z0(t){let{defaultTranscriptImportDeps:e,formatTranscriptImportResult:r,isoOf:n,parseTranscriptImportArgs:s,runTranscriptImport:o,TRANSCRIPT_IMPORT_USAGE:i}=await Promise.resolve().then(()=>(mb(),gb)),{settleHookSpoolNudges:a}=await Promise.resolve().then(()=>($r(),Hm)),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],Y0=process.argv.slice(3);Eb(V0,Y0).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});
48
48
  /*! Bundled license information:
49
49
 
50
50
  @posthog/core/dist/vendor/uuidv7.mjs: