claude-mem 13.41.0 → 14.0.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 (50) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.qoder-plugin/plugin.json +1 -1
  5. package/README.md +3 -2
  6. package/dist/bug-report/index.js +74 -74
  7. package/dist/npx-cli/index.js +146 -146
  8. package/dsh/package.json +1 -1
  9. package/openclaw/openclaw.plugin.json +1 -1
  10. package/package.json +1 -1
  11. package/plugin/.claude-plugin/plugin.json +1 -1
  12. package/plugin/.codex-plugin/plugin.json +1 -1
  13. package/plugin/.qoder-plugin/plugin.json +1 -1
  14. package/plugin/package.json +1 -1
  15. package/plugin/scripts/mcp-server.cjs +59 -59
  16. package/plugin/scripts/mcp-server.cjs.map +1 -1
  17. package/plugin/scripts/server-service.cjs +3 -3
  18. package/plugin/scripts/server-service.cjs.map +1 -1
  19. package/plugin/scripts/transcript-watcher.cjs +16 -16
  20. package/plugin/scripts/transcript-watcher.cjs.map +2 -2
  21. package/plugin/scripts/worker-service.cjs +724 -703
  22. package/plugin/scripts/worker-service.cjs.map +3 -3
  23. package/plugin/ui/viewer-bundle.js +4 -4
  24. package/plugin/ui/viewer.html +12 -0
  25. package/plugin/ui/work-view/app.js +278 -0
  26. package/plugin/ui/work-view/assets/agents/SOURCE-MANIFEST.json +42 -0
  27. package/plugin/ui/work-view/assets/agents/chatgpt.svg +2 -0
  28. package/plugin/ui/work-view/assets/agents/claude.svg +3 -0
  29. package/plugin/ui/work-view/assets/agents/gemini.svg +1 -0
  30. package/plugin/ui/work-view/assets/agents/hermes.svg +7 -0
  31. package/plugin/ui/work-view/assets/cmem-mark.svg +197 -0
  32. package/plugin/ui/work-view/assets/connect.png +0 -0
  33. package/plugin/ui/work-view/assets/fonts/HankenGrotesk-OFL.txt +94 -0
  34. package/plugin/ui/work-view/assets/fonts/HankenGrotesk.ttf +0 -0
  35. package/plugin/ui/work-view/assets/fonts/SpaceGrotesk-OFL.txt +93 -0
  36. package/plugin/ui/work-view/assets/fonts/SpaceGrotesk.ttf +0 -0
  37. package/plugin/ui/work-view/assets/icons/LICENSE +43 -0
  38. package/plugin/ui/work-view/assets/icons/arrow-left.svg +14 -0
  39. package/plugin/ui/work-view/assets/icons/chevron-down.svg +13 -0
  40. package/plugin/ui/work-view/assets/icons/filter.svg +13 -0
  41. package/plugin/ui/work-view/assets/icons/search.svg +14 -0
  42. package/plugin/ui/work-view/assets/icons/x.svg +14 -0
  43. package/plugin/ui/work-view/index.html +83 -0
  44. package/plugin/ui/work-view/live-status.js +77 -0
  45. package/plugin/ui/work-view/presentation.js +92 -0
  46. package/plugin/ui/work-view/request-views.js +133 -0
  47. package/plugin/ui/work-view/styles.css +767 -0
  48. package/plugin/ui/work-view/team-styles.css +114 -0
  49. package/plugin/ui/work-view/team-view.js +225 -0
  50. package/plugin/ui/work-view/view-model.js +228 -0
@@ -1,10 +1,10 @@
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 Eg=Object.create;var ki=Object.defineProperty;var Sg=Object.getOwnPropertyDescriptor;var yg=Object.getOwnPropertyNames;var bg=Object.getPrototypeOf,wg=Object.prototype.hasOwnProperty;var Pt=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Tg=(r,e)=>{for(var t in e)ki(r,t,{get:e[t],enumerable:!0})},Ag=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of yg(e))!wg.call(r,s)&&s!==t&&ki(r,s,{get:()=>e[s],enumerable:!(n=Sg(e,s))||n.enumerable});return r};var me=(r,e,t)=>(t=r!=null?Eg(bg(r)):{},Ag(e||!r||!r.__esModule?ki(t,"default",{value:r,enumerable:!0}):t,r));function vg(r){return(Rg??process.stderr.write.bind(process.stderr))(r)}function je(r){vg(r)}var Rg,qw,_n=Pt(()=>{"use strict";Rg=null;qw=Promise.resolve()});function xi(r){return r.replace(/^\uFEFF/,"")}function cr(r){return JSON.parse(xi(r))}function Ke(r){return cr((0,x.readFileSync)(r,"utf-8"))}function En(r){(0,x.existsSync)(r)||(0,x.mkdirSync)(r,{recursive:!0})}function pc(r){try{return(0,x.realpathSync)(r)}catch(e){if(e.code!=="ENOENT")throw e;let t=(0,te.dirname)(r);return t===r?r:(0,te.join)(pc(t),(0,te.basename)(r))}}function Sn(r){let e=r,t=new Set;try{for(;(0,x.lstatSync)(e).isSymbolicLink();){let n=(0,te.resolve)(e);if(t.has(n))throw Object.assign(new Error(`Symlink loop at ${e}`),{code:"ELOOP"});t.add(n);try{return(0,x.realpathSync)(e)}catch(s){if(s.code!=="ENOENT")throw s;let i=s instanceof Error?s:new Error(String(s));je(`claude-mem: realpathSync failed for ${e}, resolving symlink manually: ${i.message}
4
+ "use strict";var Eg=Object.create;var ki=Object.defineProperty;var Sg=Object.getOwnPropertyDescriptor;var yg=Object.getOwnPropertyNames;var bg=Object.getPrototypeOf,wg=Object.prototype.hasOwnProperty;var kt=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Tg=(r,e)=>{for(var t in e)ki(r,t,{get:e[t],enumerable:!0})},Ag=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of yg(e))!wg.call(r,s)&&s!==t&&ki(r,s,{get:()=>e[s],enumerable:!(n=Sg(e,s))||n.enumerable});return r};var me=(r,e,t)=>(t=r!=null?Eg(bg(r)):{},Ag(e||!r||!r.__esModule?ki(t,"default",{value:r,enumerable:!0}):t,r));function vg(r){return(Rg??process.stderr.write.bind(process.stderr))(r)}function je(r){vg(r)}var Rg,qw,_n=kt(()=>{"use strict";Rg=null;qw=Promise.resolve()});function xi(r){return r.replace(/^\uFEFF/,"")}function cr(r){return JSON.parse(xi(r))}function Ke(r){return cr((0,x.readFileSync)(r,"utf-8"))}function En(r){(0,x.existsSync)(r)||(0,x.mkdirSync)(r,{recursive:!0})}function pc(r){try{return(0,x.realpathSync)(r)}catch(e){if(e.code!=="ENOENT")throw e;let t=(0,te.dirname)(r);return t===r?r:(0,te.join)(pc(t),(0,te.basename)(r))}}function Sn(r){let e=r,t=new Set;try{for(;(0,x.lstatSync)(e).isSymbolicLink();){let n=(0,te.resolve)(e);if(t.has(n))throw Object.assign(new Error(`Symlink loop at ${e}`),{code:"ELOOP"});t.add(n);try{return(0,x.realpathSync)(e)}catch(s){if(s.code!=="ENOENT")throw s;let i=s instanceof Error?s:new Error(String(s));je(`claude-mem: realpathSync failed for ${e}, resolving symlink manually: ${i.message}
5
5
  `);let o=(0,x.readlinkSync)(e);e=(0,te.resolve)(pc((0,te.dirname)((0,te.resolve)(e))),o)}}}catch(n){if(n.code!=="ENOENT")throw n}return e}function K(r,e,t={}){let n=Sn(r);En((0,te.dirname)(n));let s=(0,te.dirname)(n),i=(0,te.basename)(n),o=(0,te.join)(s,`.${i}.${process.pid}.${(0,fc.randomBytes)(6).toString("hex")}.tmp`),a=Buffer.from(JSON.stringify(e,null,2)+`
6
6
  `,"utf-8"),c=t.mode;if(c===void 0)try{c=(0,x.statSync)(n).mode&511}catch{}let l;try{l=c!==void 0?(0,x.openSync)(o,"w",c):(0,x.openSync)(o,"w");let u=0;for(;u<a.length;){let d=(0,x.writeSync)(l,a,u,a.length-u);if(d===0)throw new Error(`writeSync stalled at ${u}/${a.length} bytes`);u+=d}if((0,x.fsyncSync)(l),(0,x.closeSync)(l),l=void 0,(0,x.renameSync)(o,n),!Mg){let d;try{d=(0,x.openSync)(s,"r"),(0,x.fsyncSync)(d)}catch(g){let p=g instanceof Error?g:new Error(String(g));je(`claude-mem: directory fsync failed for ${s}: ${p.message}
7
- `)}finally{if(d!==void 0)try{(0,x.closeSync)(d)}catch{}}}}catch(u){if(l!==void 0)try{(0,x.closeSync)(l)}catch{}try{(0,x.unlinkSync)(o)}catch{}throw u}}var x,fc,te,Mg,le=Pt(()=>{"use strict";x=require("fs"),fc=require("crypto"),te=require("path");_n();Mg=process.platform==="win32"});function gc(r){let e=r.env;return Og(e)&&Object.keys(e).some(t=>t.startsWith("CLAUDE_MEM_"))?"nested":"flat"}function kt(r){return gc(r)==="nested"?r.env:r}function mc(r){return gc(r)!=="nested"?r:Object.fromEntries(Object.entries(r).filter(([e])=>!e.startsWith("CLAUDE_MEM_")))}var Og,yn=Pt(()=>{"use strict";le();Og=r=>r!==null&&typeof r=="object"&&!Array.isArray(r)});function Pe(r,e=process.platform,t=(0,hc.homedir)()){return typeof r!="string"||r.length===0?r:r==="~"?t:r.startsWith("~/")||e==="win32"&&r.startsWith("~\\")?(0,_c.join)(t,r.slice(2)):r}var hc,_c,lr=Pt(()=>{"use strict";hc=require("os"),_c=require("path")});function Cg(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,N.dirname)((0,Ec.fileURLToPath)(xg.url))}function re(){if(process.env.CLAUDE_MEM_DATA_DIR)return Pe(process.env.CLAUDE_MEM_DATA_DIR);let r=(0,N.join)((0,bn.homedir)(),".claude-mem"),e=(0,N.join)(r,"settings.json");try{if((0,Di.existsSync)(e)){let t=Ke(e);if(t===null||typeof t!="object"||Array.isArray(t))return r;let n=kt(t);if(typeof n.CLAUDE_MEM_DATA_DIR=="string"&&n.CLAUDE_MEM_DATA_DIR)return Pe(n.CLAUDE_MEM_DATA_DIR)}}catch{}return r}function yc(r,e=(0,bn.homedir)(),t=process.platform){return Pe(r,t,e)}var N,bn,Di,Ec,xg,oT,U,Ig,ut,xt,Pg,ne,Sc,aT,wn,kg,j,W=Pt(()=>{"use strict";N=require("path"),bn=require("os"),Di=require("fs"),Ec=require("url");le();yn();lr();lr();xg={};oT=Cg();U=re(),Ig=(0,N.join)((0,bn.homedir)(),".claude"),ut=process.env.CLAUDE_CONFIG_DIR||Ig,xt=(0,N.join)(ut,"plugins","marketplaces","thedotmack"),Pg=(0,N.join)(U,"logs"),ne=(0,N.join)(U,"settings.json"),Sc="claude-mem.db",aT=(0,N.join)(U,Sc),wn=(0,N.join)(U,"observer-sessions"),kg=(0,N.basename)(wn);j={dataDir:()=>U,workerPid:()=>(0,N.join)(U,"worker.pid"),workerHeartbeat:()=>(0,N.join)(U,"worker-heartbeat.json"),serverPid:()=>(0,N.join)(U,".server-beta.pid"),serverPort:()=>(0,N.join)(U,".server-beta.port"),serverRuntime:()=>(0,N.join)(U,".server-beta.runtime.json"),settings:()=>(0,N.join)(U,"settings.json"),database:()=>(0,N.join)(U,Sc),chroma:()=>(0,N.join)(U,"chroma"),combinedCerts:()=>(0,N.join)(U,"combined_certs.pem"),transcriptsConfig:()=>(0,N.join)(U,"transcript-watch.json"),transcriptsState:()=>(0,N.join)(U,"transcript-watch-state.json"),corpora:()=>(0,N.join)(U,"corpora"),supervisorRegistry:()=>(0,N.join)(U,"supervisor.json"),envFile:()=>(0,N.join)(U,".env"),logsDir:()=>Pg}});var se,Ac,Ni,Li,Fi,f,M=Pt(()=>{"use strict";se=require("fs"),Ac=require("path");W();_n();le();yn();Ni=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(Ni||{}),Li=null,Fi=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;logFileDate=null;logFd=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 t=this.logFileDate!==e;this.closeLogFd(),this.logFileInitialized=!1,this.logFileDate=e;try{let n=j.logsDir();(0,se.existsSync)(n)||(0,se.mkdirSync)(n,{recursive:!0}),this.logFilePath=(0,Ac.join)(n,`claude-mem-${e}.log`),this.logFileInitialized=!0}catch(n){t&&console.error("[LOGGER] Failed to initialize log file:",n instanceof Error?n.message:String(n)),this.logFilePath=null}}closeLogFd(){if(this.logFd!==null){try{(0,se.closeSync)(this.logFd)}catch{}this.logFd=null}}appendLine(e,t){if(this.logFd!==null){let n=!1;try{let s=(0,se.fstatSync)(this.logFd),i=(0,se.statSync)(e);n=s.ino===i.ino&&s.dev===i.dev}catch{}n||this.closeLogFd()}this.logFd===null&&(this.logFd=(0,se.openSync)(e,"a"));try{let n=Buffer.from(t,"utf8");for(;n.length>0;){let s=(0,se.writeSync)(this.logFd,n);if(s<=0)throw new Error("log write accepted 0 bytes");n=n.subarray(s)}}catch(n){throw this.closeLogFd(),n}}getLevel(){if(this.level===null)try{let e=j.settings();if((0,se.existsSync)(e)){let n=(kt(Ke(e)).CLAUDE_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=Ni[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,t,n=6){let s=new WeakSet,i=(o,a)=>{if(typeof o=="bigint")return`${o}n`;if(o===null||typeof o!="object")return o;let c=o.toJSON,l=typeof c=="function"?c.call(o):o;if(typeof l=="bigint")return`${l}n`;if(l===null||typeof l!="object")return l;if(s.has(l))return"[Circular]";if(a>=n)return Array.isArray(l)?"[Array]":"[Object]";s.add(l);try{if(Array.isArray(l))return l.map(d=>i(d,a+1));let u={};for(let d of Object.keys(l))try{u[d]=i(l[d],a+1)}catch{u[d]="[unreadable]"}return u}finally{s.delete(l)}};try{return JSON.stringify(i(e,0),null,t)??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}
7
+ `)}finally{if(d!==void 0)try{(0,x.closeSync)(d)}catch{}}}}catch(u){if(l!==void 0)try{(0,x.closeSync)(l)}catch{}try{(0,x.unlinkSync)(o)}catch{}throw u}}var x,fc,te,Mg,le=kt(()=>{"use strict";x=require("fs"),fc=require("crypto"),te=require("path");_n();Mg=process.platform==="win32"});function gc(r){let e=r.env;return Og(e)&&Object.keys(e).some(t=>t.startsWith("CLAUDE_MEM_"))?"nested":"flat"}function xt(r){return gc(r)==="nested"?r.env:r}function mc(r){return gc(r)!=="nested"?r:Object.fromEntries(Object.entries(r).filter(([e])=>!e.startsWith("CLAUDE_MEM_")))}var Og,yn=kt(()=>{"use strict";le();Og=r=>r!==null&&typeof r=="object"&&!Array.isArray(r)});function Pe(r,e=process.platform,t=(0,hc.homedir)()){return typeof r!="string"||r.length===0?r:r==="~"?t:r.startsWith("~/")||e==="win32"&&r.startsWith("~\\")?(0,_c.join)(t,r.slice(2)):r}var hc,_c,lr=kt(()=>{"use strict";hc=require("os"),_c=require("path")});function Cg(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,N.dirname)((0,Ec.fileURLToPath)(xg.url))}function re(){if(process.env.CLAUDE_MEM_DATA_DIR)return Pe(process.env.CLAUDE_MEM_DATA_DIR);let r=(0,N.join)((0,bn.homedir)(),".claude-mem"),e=(0,N.join)(r,"settings.json");try{if((0,Di.existsSync)(e)){let t=Ke(e);if(t===null||typeof t!="object"||Array.isArray(t))return r;let n=xt(t);if(typeof n.CLAUDE_MEM_DATA_DIR=="string"&&n.CLAUDE_MEM_DATA_DIR)return Pe(n.CLAUDE_MEM_DATA_DIR)}}catch{}return r}function yc(r,e=(0,bn.homedir)(),t=process.platform){return Pe(r,t,e)}var N,bn,Di,Ec,xg,oT,U,Ig,ut,Dt,Pg,ne,Sc,aT,wn,kg,j,W=kt(()=>{"use strict";N=require("path"),bn=require("os"),Di=require("fs"),Ec=require("url");le();yn();lr();lr();xg={};oT=Cg();U=re(),Ig=(0,N.join)((0,bn.homedir)(),".claude"),ut=process.env.CLAUDE_CONFIG_DIR||Ig,Dt=(0,N.join)(ut,"plugins","marketplaces","thedotmack"),Pg=(0,N.join)(U,"logs"),ne=(0,N.join)(U,"settings.json"),Sc="claude-mem.db",aT=(0,N.join)(U,Sc),wn=(0,N.join)(U,"observer-sessions"),kg=(0,N.basename)(wn);j={dataDir:()=>U,workerPid:()=>(0,N.join)(U,"worker.pid"),workerHeartbeat:()=>(0,N.join)(U,"worker-heartbeat.json"),serverPid:()=>(0,N.join)(U,".server-beta.pid"),serverPort:()=>(0,N.join)(U,".server-beta.port"),serverRuntime:()=>(0,N.join)(U,".server-beta.runtime.json"),settings:()=>(0,N.join)(U,"settings.json"),database:()=>(0,N.join)(U,Sc),chroma:()=>(0,N.join)(U,"chroma"),combinedCerts:()=>(0,N.join)(U,"combined_certs.pem"),transcriptsConfig:()=>(0,N.join)(U,"transcript-watch.json"),transcriptsState:()=>(0,N.join)(U,"transcript-watch-state.json"),corpora:()=>(0,N.join)(U,"corpora"),supervisorRegistry:()=>(0,N.join)(U,"supervisor.json"),envFile:()=>(0,N.join)(U,".env"),logsDir:()=>Pg}});var se,Ac,Ni,Li,Fi,f,M=kt(()=>{"use strict";se=require("fs"),Ac=require("path");W();_n();le();yn();Ni=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(Ni||{}),Li=null,Fi=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;logFileDate=null;logFd=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 t=this.logFileDate!==e;this.closeLogFd(),this.logFileInitialized=!1,this.logFileDate=e;try{let n=j.logsDir();(0,se.existsSync)(n)||(0,se.mkdirSync)(n,{recursive:!0}),this.logFilePath=(0,Ac.join)(n,`claude-mem-${e}.log`),this.logFileInitialized=!0}catch(n){t&&console.error("[LOGGER] Failed to initialize log file:",n instanceof Error?n.message:String(n)),this.logFilePath=null}}closeLogFd(){if(this.logFd!==null){try{(0,se.closeSync)(this.logFd)}catch{}this.logFd=null}}appendLine(e,t){if(this.logFd!==null){let n=!1;try{let s=(0,se.fstatSync)(this.logFd),i=(0,se.statSync)(e);n=s.ino===i.ino&&s.dev===i.dev}catch{}n||this.closeLogFd()}this.logFd===null&&(this.logFd=(0,se.openSync)(e,"a"));try{let n=Buffer.from(t,"utf8");for(;n.length>0;){let s=(0,se.writeSync)(this.logFd,n);if(s<=0)throw new Error("log write accepted 0 bytes");n=n.subarray(s)}}catch(n){throw this.closeLogFd(),n}}getLevel(){if(this.level===null)try{let e=j.settings();if((0,se.existsSync)(e)){let n=(xt(Ke(e)).CLAUDE_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=Ni[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,t,n=6){let s=new WeakSet,i=(o,a)=>{if(typeof o=="bigint")return`${o}n`;if(o===null||typeof o!="object")return o;let c=o.toJSON,l=typeof c=="function"?c.call(o):o;if(typeof l=="bigint")return`${l}n`;if(l===null||typeof l!="object")return l;if(s.has(l))return"[Circular]";if(a>=n)return Array.isArray(l)?"[Array]":"[Object]";s.add(l);try{if(Array.isArray(l))return l.map(d=>i(d,a+1));let u={};for(let d of Object.keys(l))try{u[d]=i(l[d],a+1)}catch{u[d]="[unreadable]"}return u}finally{s.delete(l)}};try{return JSON.stringify(i(e,0),null,t)??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 t=Object.keys(e);return t.length===0?"{}":t.length<=3?this.safeStringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(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 t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${s} ${i}:${o}:${a}.${c}`}log(e,t,n,s,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=Ni[e].padEnd(5),c=t.padEnd(6),l="";s?.correlationId?l=`[${s.correlationId}] `:s?.sessionId&&(l=`[session-${s.sessionId}] `);let u="";i!=null&&(i instanceof Error?u=this.getLevel()===0?`
9
9
  ${i.message}
10
10
  ${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?u=`
@@ -12,29 +12,29 @@ ${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?u=`
12
12
  `)}catch(p){let m=p instanceof Error?p:new Error(String(p));je(`[LOGGER] Failed to write to log file: ${m.message}
13
13
  ${m.stack??""}
14
14
  `)}else je(g+`
15
- `)}debug(e,t,n,s){this.log(0,e,t,n,s)}info(e,t,n,s){this.log(1,e,t,n,s)}warn(e,t,n,s){this.log(2,e,t,n,s)}setErrorSink(e){Li=e}error(e,t,n,s){this.log(3,e,t,n,s),this.routeErrorToSink(t,n,s)}routeErrorToSink(e,t,n){try{if(!Li||!(n instanceof Error))return;Li(n)}catch{}}dataIn(e,t,n,s){this.info(e,`\u2192 ${t}`,n,s)}dataOut(e,t,n,s){this.info(e,`\u2190 ${t}`,n,s)}success(e,t,n,s){this.info(e,`\u2713 ${t}`,n,s)}failure(e,t,n,s){this.error(e,`\u2717 ${t}`,n,s)}},f=new Fi});var hg=require("fs");W();var dt=require("fs"),Xe=require("path"),dr=require("os");var Q={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Dg=300,bc={min:60,max:86400};function wc(r=process.env){let e=Number.parseInt(r.CLAUDE_MEM_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=bc.min&&e<=bc.max?e:Dg}var ke={SUCCESS:0};function Lg(r=process.platform){return r==="win32"?8e3:5e3}function ur(r=process.platform){return Q.SESSION_INIT_HOOK_CAP-Lg(r)}function Tc(r=process.platform){return r==="win32"?ur(r):Q.SESSION_INIT_REQUEST_MAX}function xe(r){return process.platform==="win32"?Math.round(r*Q.WINDOWS_MULTIPLIER):r}le();M();function Rc(r){try{return new URL(r).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}yn();var Ng="security_alert",Fg="sync-hub.black-pond-afbb.workers.dev",Ug="ziczmqtpmaxbornfghye.supabase.co",$g="https://sync.cmem.ai",Bg=new Set(["xiaomi/mimo-v2-flash:free"]);function Wg(r){return typeof r=="boolean"?String(r):r}function Hg(r){let e=r.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!Bg.has(e.trim()))return!1;let t=typeof r.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?r.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return t===""||Rc(t)}var vc=18e4,Mc=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];function Cc(r,e){return(0,Xe.join)((0,Xe.dirname)(r),`.${(0,Xe.basename)(r)}.${e.markerTag}`)}function Ui(r,e){try{(0,dt.writeFileSync)(Cc(r,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Oc=new Set;function jg(r){if(typeof r!="string")return null;let e=r.trim();if(e.length===0)return null;try{let t=new URL(e).hostname;if(t===Fg||t===Ug)return $g}catch{return null}return null}var H=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(xe(Q.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ur()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,Xe.join)((0,dr.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Xe.join)((0,dr.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,dr.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(vc),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(vc),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let t=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(t):t}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,t){let n=t?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0,n={}){try{if(!(0,dt.existsSync)(e)){let g=this.getAllDefaults();if(!n.readOnly)try{K(e,g,{mode:384});for(let p of Mc)Ui(e,p);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(p){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,p instanceof Error?p.message:String(p))}return this.finalizeSettings(g,t)}let s=(0,dt.readFileSync)(e,"utf-8"),i=cr(s),o=kt(i),a=o!==i,c=mc(i),l=a&&Object.keys(c).some(g=>g!=="env");if(a&&!l&&!n.readOnly)try{K(e,o,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(g){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,g instanceof Error?g.message:String(g))}if(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Ng&&(o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!n.readOnly))try{K(e,l?{...c,env:o}:o,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(g){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,g instanceof Error?g.message:String(g))}if(Hg(o)){let g=String(o.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(o={...o,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!n.readOnly)try{K(e,l?{...c,env:o}:o,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${g} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(p){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,p instanceof Error?p.message:String(p))}}let u=jg(o.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(o={...o,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!n.readOnly))try{K(e,l?{...c,env:o}:o,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",u,"from a retired hub host:",e)}catch(g){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,g instanceof Error?g.message:String(g))}for(let g of Mc)if(!(0,dt.existsSync)(Cc(e,g))){if(o[g.key]!==g.legacy){n.readOnly||Ui(e,g);continue}if(o={...o,[g.key]:this.DEFAULTS[g.key]},!n.readOnly)try{K(e,l?{...c,env:o}:o,{mode:384}),Ui(e,g),console.warn(`[SETTINGS] Migrated ${g.key} off the old ${g.legacy}ms default to ${this.DEFAULTS[g.key]}ms:`,e)}catch(p){let m=`${g.key}\0${e}`;Oc.has(m)||(Oc.add(m),console.warn(`[SETTINGS] Failed to migrate ${g.key}; using the new default in memory (reported once per process):`,e,p instanceof Error?p.message:String(p)))}}let d={...this.DEFAULTS};for(let g of Object.keys(this.DEFAULTS))o[g]!==void 0&&(d[g]=Wg(o[g]));return this.finalizeSettings(d,t)}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return this.finalizeSettings(i,t)}}};var ft=require("fs"),Pc=require("os"),An=require("path");le();W();var Dt=j.transcriptsConfig(),Rn=j.transcriptsState(),Kg={version:1,schemas:{},watches:[],stateFile:Rn};function kc(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=ie(r.path).replace(/\\/g,"/"),s=(0,An.join)((0,Pc.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function xc(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&kc(r)}var Gg={path:"payload.source.subagent.thread_spawn"};function Dc(r,e){if(e.CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION==="true")return{config:r,scoped:0,removed:0};let t=e.CLAUDE_MEM_CODEX_SUBAGENT_INGESTION==="true"&&e.CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS!=="true",n=0,s=0,i=[];for(let o of r.watches)kc(o)?t?(n+=1,i.push({...o,subagentOnly:!0,subagentSource:{...Gg}})):s+=1:i.push(o);return{config:{...r,watches:i},scoped:n,removed:s}}function ie(r){return r&&yc(r)}var Ae=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Ic={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 D(r,e,t){if(!r)throw new Error(`${e} ${t}`)}function fr(r,e){D(r===void 0||typeof r=="string",e,"must be a string")}function Tn(r,e){D(typeof r=="string"&&r.trim().length>0,e,"must be a non-empty string")}function Lc(r,e){D(r===void 0||typeof r=="boolean",e,"must be true or false")}function Nc(r,e){typeof r!="string"&&(D(Ae(r),e,"must be a path string or an object"),fr(r.path,`${e}.path`),r.coalesce!==void 0&&(D(Array.isArray(r.coalesce),`${e}.coalesce`,"must be an array"),r.coalesce.forEach((t,n)=>Nc(t,`${e}.coalesce[${n}]`))))}function Fc(r,e){D(Ae(r),e,"must be an object");for(let t of["path","regex","contains","not_contains","starts_with","not_starts_with"])fr(r[t],`${e}.${t}`);if(typeof r.regex=="string")try{new RegExp(r.regex)}catch{D(!1,`${e}.regex`,"must be a valid regular expression")}Lc(r.exists,`${e}.exists`);for(let t of["in","not_in"])D(r[t]===void 0||Array.isArray(r[t]),`${e}.${t}`,"must be an array");for(let t of["all","any"]){let n=r[t];n!==void 0&&(D(Array.isArray(n),`${e}.${t}`,"must be an array"),n.forEach((s,i)=>Fc(s,`${e}.${t}[${i}]`)))}}function $i(r,e){D(Ae(r),e,"must be an object"),Tn(r.name,`${e}.name`);for(let t of["eventTypePath","sessionIdPath","cwdPath","projectPath"])fr(r[t],`${e}.${t}`);D(Array.isArray(r.events),`${e}.events`,"must be an array"),r.events.forEach((t,n)=>{let s=`${e}.events[${n}]`;if(D(Ae(t),s,"must be an object"),D(typeof t.name=="string",`${s}.name`,"must be a string"),D(typeof t.action=="string"&&Object.hasOwn(Ic,t.action),`${s}.action`,`must be one of ${Object.keys(Ic).join(", ")}`),t.match!==void 0&&Fc(t.match,`${s}.match`),t.fields!==void 0){D(Ae(t.fields),`${s}.fields`,"must be an object");for(let[i,o]of Object.entries(t.fields))Nc(o,`${s}.fields.${i}`)}})}function zg(r,e,t){D(Ae(r),e,"must be an object"),Tn(r.name,`${e}.name`),Tn(r.path,`${e}.path`);for(let o of["workspace","project","agentId"])fr(r[o],`${e}.${o}`);for(let o of["startAtEnd","subagentOnly"])Lc(r[o],`${e}.${o}`);let{subagentSource:n,context:s}=r;if(n!==void 0&&(D(Ae(n),`${e}.subagentSource`,"must be an object"),D(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(D(Ae(s),`${e}.context`,"must be an object"),D(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),fr(s.path,`${e}.context.path`),s.updateOn!==void 0&&(D(Array.isArray(s.updateOn),`${e}.context.updateOn`,"must be an array"),s.updateOn.forEach((o,a)=>D(o==="session_start"||o==="session_end",`${e}.context.updateOn[${a}]`,'must be "session_start" or "session_end"')))),typeof r.schema!="string"){D(Ae(r.schema),`${e}.schema`,"must be a schema name or an inline schema object"),$i(r.schema,`${e}.schema`);return}Tn(r.schema,`${e}.schema`);let i=t?.[r.schema];i!==void 0&&$i(i,`schemas.${r.schema}`)}function Vg(r){D(Ae(r),"the top level","must be an object"),D(r.version===1,"version","must be 1");let{stateFile:e,schemas:t,watches:n}=r;if(D(e==null||typeof e=="string","stateFile","must be a string"),t!==void 0){D(Ae(t),"schemas","must be an object");for(let[s,i]of Object.entries(t))$i(i,`schemas.${s}`)}D(Array.isArray(n),"watches","must be an array"),n.forEach((s,i)=>zg(s,`watches[${i}]`,t))}function Bi(r=Dt){let e=ie(r);if(!(0,ft.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=Ke(e);try{Vg(t)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`Invalid transcript watch config: ${e} (${s})`,{cause:n})}return t.stateFile||(t.stateFile=Rn),t}function Wi(r=Dt){let e=ie(r),t=(0,An.dirname)(e);(0,ft.existsSync)(t)||(0,ft.mkdirSync)(t,{recursive:!0}),(0,ft.writeFileSync)(e,JSON.stringify(Kg,null,2))}var dg=require("crypto"),B=require("fs"),fg=require("fs/promises"),z=require("path");M();var pr=require("fs"),$c=require("path");M();le();function De(r,e){return typeof r!="object"||r===null||Array.isArray(r)?{}:Object.fromEntries(Object.entries(r).filter(t=>e(t[1])))}function Bc(r){try{if(!(0,pr.existsSync)(r))return{offsets:{}};let e=Ke(r);if(!e||typeof e!="object"||Array.isArray(e))return{offsets:{}};let t=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,n=o=>typeof o=="string",s={offsets:De(e.offsets,t)},i=o=>Object.fromEntries(Object.entries(o).filter(([a])=>Object.hasOwn(s.offsets,a)));if(e.partials!==void 0&&(s.partials=i(De(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=i(De(e.partialBytes,o=>typeof o=="string"&&o.length>0&&Buffer.from(o,"base64").toString("base64")===o))),e.frameLines!==void 0&&(s.frameLines=i(De(e.frameLines,t))),e.fileIdentities!==void 0&&(s.fileIdentities=i(De(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=i(De(e.checkpointFingerprints,n))),e.pendingTools!==void 0){let o=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),a=c=>o(c)&&typeof c.toolName=="string"&&c.toolName.length>0;s.pendingTools=Object.fromEntries(Object.entries(i(De(e.pendingTools,o))).map(([c,l])=>[c,Object.fromEntries(Object.entries(De(l,o)).map(([u,d])=>[u,De(d,a)]))]))}return e.cwds!==void 0&&(s.cwds=De(e.cwds,n)),s}catch(e){return f.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}var qg=64*1024,Uc=new WeakMap;function Yg(r){let e=Uc.get(r);return e||(e=(r.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(r.toolInput)??""))<=qg?r:{toolName:r.toolName},Uc.set(r,e)),e}function Jg(r){let e={};for(let[t,n]of Object.entries(r)){e[t]={};for(let[s,i]of Object.entries(n)){e[t][s]={};for(let[o,a]of Object.entries(i))e[t][s][o]=Yg(a)}}return e}function gr(r,e){try{let t=(0,$c.dirname)(r);(0,pr.existsSync)(t)||(0,pr.mkdirSync)(t,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:Jg(e.pendingTools)}:e;K(r,n,{mode:384})}catch(t){f.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var pn=me(require("path"),1);var F=me(require("path"),1),gu=require("crypto"),k=require("fs");M();var Hi=class extends Error{constructor(t){super(`SSE event exceeded ${t} bytes`);this.maxEventBytes=t;this.name="SseEventTooLargeError"}maxEventBytes},ji=class extends Error{constructor(t){super(`SSE stream ended before a terminal event (${t.join(", ")})`);this.terminalEventNames=t;this.name="StreamEndedEarlyError"}terminalEventNames},Wc=13,Hc=10,Xg=58;async function*Qg(r){if(!(r instanceof ReadableStream)){yield*r;return}let e=r.getReader(),t=!1;try{for(;;){let{done:n,value:s}=await e.read();if(n){t=!0;return}yield s}}finally{try{t||await e.cancel()}finally{e.releaseLock()}}}function Zg(r,e){if(r.length===1)return r[0];let t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}async function*jc(r,e={}){let t=e.maxEventBytes??1048576,n=new TextDecoder,s=[],i=0,o=!1,a=0,c=null,l,u=null,d=!1,g=m=>{if(a+m>t)throw new Hi(t)},p=m=>{if(m.length===0){let R=c!==null||u!==null?{event:c||"message",data:(u??[]).join(`
15
+ `)}debug(e,t,n,s){this.log(0,e,t,n,s)}info(e,t,n,s){this.log(1,e,t,n,s)}warn(e,t,n,s){this.log(2,e,t,n,s)}setErrorSink(e){Li=e}error(e,t,n,s){this.log(3,e,t,n,s),this.routeErrorToSink(t,n,s)}routeErrorToSink(e,t,n){try{if(!Li||!(n instanceof Error))return;Li(n)}catch{}}dataIn(e,t,n,s){this.info(e,`\u2192 ${t}`,n,s)}dataOut(e,t,n,s){this.info(e,`\u2190 ${t}`,n,s)}success(e,t,n,s){this.info(e,`\u2713 ${t}`,n,s)}failure(e,t,n,s){this.error(e,`\u2717 ${t}`,n,s)}},f=new Fi});var hg=require("fs");W();var dt=require("fs"),Xe=require("path"),dr=require("os");var Q={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Dg=300,bc={min:60,max:86400};function wc(r=process.env){let e=Number.parseInt(r.CLAUDE_MEM_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=bc.min&&e<=bc.max?e:Dg}var ke={SUCCESS:0};function Lg(r=process.platform){return r==="win32"?8e3:5e3}function ur(r=process.platform){return Q.SESSION_INIT_HOOK_CAP-Lg(r)}function Tc(r=process.platform){return r==="win32"?ur(r):Q.SESSION_INIT_REQUEST_MAX}function xe(r){return process.platform==="win32"?Math.round(r*Q.WINDOWS_MULTIPLIER):r}le();M();function Rc(r){try{return new URL(r).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}yn();var Ng="security_alert",Fg="sync-hub.black-pond-afbb.workers.dev",Ug="ziczmqtpmaxbornfghye.supabase.co",$g="https://sync.cmem.ai",Bg=new Set(["xiaomi/mimo-v2-flash:free"]);function Wg(r){return typeof r=="boolean"?String(r):r}function Hg(r){let e=r.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!Bg.has(e.trim()))return!1;let t=typeof r.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?r.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return t===""||Rc(t)}var vc=18e4,Mc=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];function Cc(r,e){return(0,Xe.join)((0,Xe.dirname)(r),`.${(0,Xe.basename)(r)}.${e.markerTag}`)}function Ui(r,e){try{(0,dt.writeFileSync)(Cc(r,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Oc=new Set;function jg(r){if(typeof r!="string")return null;let e=r.trim();if(e.length===0)return null;try{let t=new URL(e).hostname;if(t===Fg||t===Ug)return $g}catch{return null}return null}var H=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(xe(Q.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ur()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,Xe.join)((0,dr.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Xe.join)((0,dr.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,dr.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(vc),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(vc),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let t=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(t):t}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,t){let n=t?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0,n={}){try{if(!(0,dt.existsSync)(e)){let g=this.getAllDefaults();if(!n.readOnly)try{K(e,g,{mode:384});for(let p of Mc)Ui(e,p);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(p){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,p instanceof Error?p.message:String(p))}return this.finalizeSettings(g,t)}let s=(0,dt.readFileSync)(e,"utf-8"),i=cr(s),o=xt(i),a=o!==i,c=mc(i),l=a&&Object.keys(c).some(g=>g!=="env");if(a&&!l&&!n.readOnly)try{K(e,o,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(g){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,g instanceof Error?g.message:String(g))}if(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Ng&&(o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!n.readOnly))try{K(e,l?{...c,env:o}:o,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(g){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,g instanceof Error?g.message:String(g))}if(Hg(o)){let g=String(o.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(o={...o,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!n.readOnly)try{K(e,l?{...c,env:o}:o,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${g} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(p){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,p instanceof Error?p.message:String(p))}}let u=jg(o.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(o={...o,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!n.readOnly))try{K(e,l?{...c,env:o}:o,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",u,"from a retired hub host:",e)}catch(g){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,g instanceof Error?g.message:String(g))}for(let g of Mc)if(!(0,dt.existsSync)(Cc(e,g))){if(o[g.key]!==g.legacy){n.readOnly||Ui(e,g);continue}if(o={...o,[g.key]:this.DEFAULTS[g.key]},!n.readOnly)try{K(e,l?{...c,env:o}:o,{mode:384}),Ui(e,g),console.warn(`[SETTINGS] Migrated ${g.key} off the old ${g.legacy}ms default to ${this.DEFAULTS[g.key]}ms:`,e)}catch(p){let m=`${g.key}\0${e}`;Oc.has(m)||(Oc.add(m),console.warn(`[SETTINGS] Failed to migrate ${g.key}; using the new default in memory (reported once per process):`,e,p instanceof Error?p.message:String(p)))}}let d={...this.DEFAULTS};for(let g of Object.keys(this.DEFAULTS))o[g]!==void 0&&(d[g]=Wg(o[g]));return this.finalizeSettings(d,t)}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return this.finalizeSettings(i,t)}}};var ft=require("fs"),Pc=require("os"),An=require("path");le();W();var Lt=j.transcriptsConfig(),Rn=j.transcriptsState(),Kg={version:1,schemas:{},watches:[],stateFile:Rn};function kc(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=ie(r.path).replace(/\\/g,"/"),s=(0,An.join)((0,Pc.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function xc(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&kc(r)}var Gg={path:"payload.source.subagent.thread_spawn"};function Dc(r,e){if(e.CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION==="true")return{config:r,scoped:0,removed:0};let t=e.CLAUDE_MEM_CODEX_SUBAGENT_INGESTION==="true"&&e.CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS!=="true",n=0,s=0,i=[];for(let o of r.watches)kc(o)?t?(n+=1,i.push({...o,subagentOnly:!0,subagentSource:{...Gg}})):s+=1:i.push(o);return{config:{...r,watches:i},scoped:n,removed:s}}function ie(r){return r&&yc(r)}var Ae=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Ic={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 D(r,e,t){if(!r)throw new Error(`${e} ${t}`)}function fr(r,e){D(r===void 0||typeof r=="string",e,"must be a string")}function Tn(r,e){D(typeof r=="string"&&r.trim().length>0,e,"must be a non-empty string")}function Lc(r,e){D(r===void 0||typeof r=="boolean",e,"must be true or false")}function Nc(r,e){typeof r!="string"&&(D(Ae(r),e,"must be a path string or an object"),fr(r.path,`${e}.path`),r.coalesce!==void 0&&(D(Array.isArray(r.coalesce),`${e}.coalesce`,"must be an array"),r.coalesce.forEach((t,n)=>Nc(t,`${e}.coalesce[${n}]`))))}function Fc(r,e){D(Ae(r),e,"must be an object");for(let t of["path","regex","contains","not_contains","starts_with","not_starts_with"])fr(r[t],`${e}.${t}`);if(typeof r.regex=="string")try{new RegExp(r.regex)}catch{D(!1,`${e}.regex`,"must be a valid regular expression")}Lc(r.exists,`${e}.exists`);for(let t of["in","not_in"])D(r[t]===void 0||Array.isArray(r[t]),`${e}.${t}`,"must be an array");for(let t of["all","any"]){let n=r[t];n!==void 0&&(D(Array.isArray(n),`${e}.${t}`,"must be an array"),n.forEach((s,i)=>Fc(s,`${e}.${t}[${i}]`)))}}function $i(r,e){D(Ae(r),e,"must be an object"),Tn(r.name,`${e}.name`);for(let t of["eventTypePath","sessionIdPath","cwdPath","projectPath"])fr(r[t],`${e}.${t}`);D(Array.isArray(r.events),`${e}.events`,"must be an array"),r.events.forEach((t,n)=>{let s=`${e}.events[${n}]`;if(D(Ae(t),s,"must be an object"),D(typeof t.name=="string",`${s}.name`,"must be a string"),D(typeof t.action=="string"&&Object.hasOwn(Ic,t.action),`${s}.action`,`must be one of ${Object.keys(Ic).join(", ")}`),t.match!==void 0&&Fc(t.match,`${s}.match`),t.fields!==void 0){D(Ae(t.fields),`${s}.fields`,"must be an object");for(let[i,o]of Object.entries(t.fields))Nc(o,`${s}.fields.${i}`)}})}function zg(r,e,t){D(Ae(r),e,"must be an object"),Tn(r.name,`${e}.name`),Tn(r.path,`${e}.path`);for(let o of["workspace","project","agentId"])fr(r[o],`${e}.${o}`);for(let o of["startAtEnd","subagentOnly"])Lc(r[o],`${e}.${o}`);let{subagentSource:n,context:s}=r;if(n!==void 0&&(D(Ae(n),`${e}.subagentSource`,"must be an object"),D(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(D(Ae(s),`${e}.context`,"must be an object"),D(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),fr(s.path,`${e}.context.path`),s.updateOn!==void 0&&(D(Array.isArray(s.updateOn),`${e}.context.updateOn`,"must be an array"),s.updateOn.forEach((o,a)=>D(o==="session_start"||o==="session_end",`${e}.context.updateOn[${a}]`,'must be "session_start" or "session_end"')))),typeof r.schema!="string"){D(Ae(r.schema),`${e}.schema`,"must be a schema name or an inline schema object"),$i(r.schema,`${e}.schema`);return}Tn(r.schema,`${e}.schema`);let i=t?.[r.schema];i!==void 0&&$i(i,`schemas.${r.schema}`)}function Vg(r){D(Ae(r),"the top level","must be an object"),D(r.version===1,"version","must be 1");let{stateFile:e,schemas:t,watches:n}=r;if(D(e==null||typeof e=="string","stateFile","must be a string"),t!==void 0){D(Ae(t),"schemas","must be an object");for(let[s,i]of Object.entries(t))$i(i,`schemas.${s}`)}D(Array.isArray(n),"watches","must be an array"),n.forEach((s,i)=>zg(s,`watches[${i}]`,t))}function Bi(r=Lt){let e=ie(r);if(!(0,ft.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=Ke(e);try{Vg(t)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`Invalid transcript watch config: ${e} (${s})`,{cause:n})}return t.stateFile||(t.stateFile=Rn),t}function Wi(r=Lt){let e=ie(r),t=(0,An.dirname)(e);(0,ft.existsSync)(t)||(0,ft.mkdirSync)(t,{recursive:!0}),(0,ft.writeFileSync)(e,JSON.stringify(Kg,null,2))}var dg=require("crypto"),B=require("fs"),fg=require("fs/promises"),z=require("path");M();var pr=require("fs"),$c=require("path");M();le();function De(r,e){return typeof r!="object"||r===null||Array.isArray(r)?{}:Object.fromEntries(Object.entries(r).filter(t=>e(t[1])))}function Bc(r){try{if(!(0,pr.existsSync)(r))return{offsets:{}};let e=Ke(r);if(!e||typeof e!="object"||Array.isArray(e))return{offsets:{}};let t=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,n=o=>typeof o=="string",s={offsets:De(e.offsets,t)},i=o=>Object.fromEntries(Object.entries(o).filter(([a])=>Object.hasOwn(s.offsets,a)));if(e.partials!==void 0&&(s.partials=i(De(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=i(De(e.partialBytes,o=>typeof o=="string"&&o.length>0&&Buffer.from(o,"base64").toString("base64")===o))),e.frameLines!==void 0&&(s.frameLines=i(De(e.frameLines,t))),e.fileIdentities!==void 0&&(s.fileIdentities=i(De(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=i(De(e.checkpointFingerprints,n))),e.pendingTools!==void 0){let o=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),a=c=>o(c)&&typeof c.toolName=="string"&&c.toolName.length>0;s.pendingTools=Object.fromEntries(Object.entries(i(De(e.pendingTools,o))).map(([c,l])=>[c,Object.fromEntries(Object.entries(De(l,o)).map(([u,d])=>[u,De(d,a)]))]))}return e.cwds!==void 0&&(s.cwds=De(e.cwds,n)),s}catch(e){return f.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}var qg=64*1024,Uc=new WeakMap;function Yg(r){let e=Uc.get(r);return e||(e=(r.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(r.toolInput)??""))<=qg?r:{toolName:r.toolName},Uc.set(r,e)),e}function Jg(r){let e={};for(let[t,n]of Object.entries(r)){e[t]={};for(let[s,i]of Object.entries(n)){e[t][s]={};for(let[o,a]of Object.entries(i))e[t][s][o]=Yg(a)}}return e}function gr(r,e){try{let t=(0,$c.dirname)(r);(0,pr.existsSync)(t)||(0,pr.mkdirSync)(t,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:Jg(e.pendingTools)}:e;K(r,n,{mode:384})}catch(t){f.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var pn=me(require("path"),1);var F=me(require("path"),1),gu=require("crypto"),k=require("fs");M();var Hi=class extends Error{constructor(t){super(`SSE event exceeded ${t} bytes`);this.maxEventBytes=t;this.name="SseEventTooLargeError"}maxEventBytes},ji=class extends Error{constructor(t){super(`SSE stream ended before a terminal event (${t.join(", ")})`);this.terminalEventNames=t;this.name="StreamEndedEarlyError"}terminalEventNames},Wc=13,Hc=10,Xg=58;async function*Qg(r){if(!(r instanceof ReadableStream)){yield*r;return}let e=r.getReader(),t=!1;try{for(;;){let{done:n,value:s}=await e.read();if(n){t=!0;return}yield s}}finally{try{t||await e.cancel()}finally{e.releaseLock()}}}function Zg(r,e){if(r.length===1)return r[0];let t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}async function*jc(r,e={}){let t=e.maxEventBytes??1048576,n=new TextDecoder,s=[],i=0,o=!1,a=0,c=null,l,u=null,d=!1,g=m=>{if(a+m>t)throw new Hi(t)},p=m=>{if(m.length===0){let R=c!==null||u!==null?{event:c||"message",data:(u??[]).join(`
16
16
  `),...l!==void 0?{id:l}:{}}:null;return c=null,l=void 0,u=null,a=0,R}if(m[0]===Xg)return e.onActivity?.(),null;g(m.length),a+=m.length;let h=n.decode(m),_=h.indexOf(":"),E=_===-1?h:h.slice(0,_),y=_===-1?"":h.slice(_+1);return y.startsWith(" ")&&(y=y.slice(1)),E==="event"?c=y:E==="data"?(u??=[]).push(y):E==="id"&&(l=y),null};for await(let m of Qg(r)){let h=0;for(let _=0;_<m.length;_++){let E=m[_];if(o&&(o=!1,E===Hc)){h=_+1;continue}if(E!==Wc&&E!==Hc)continue;s.push(m.subarray(h,_));let y=Zg(s,i+(_-h));s=[],i=0;let w=p(y);w&&(e.terminalEventNames?.includes(w.event)&&(d=!0),yield w),o=E===Wc,h=_+1}if(h<m.length){let _=m.slice(h);s.push(_),i+=_.length,g(i)}}if(e.terminalEventNames&&e.terminalEventNames.length>0&&!d)throw new ji(e.terminalEventNames)}W();W();var vn=null;function Y(){return vn!==null||(vn=H.loadFromFile(ne)),vn}function Mn(r){return(r.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}function mr(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}var gt=require("fs");M();var Ki=require("node:child_process");function Gi(r,e,t){return(0,Ki.spawn)(r,e??[],{...t,windowsHide:!0})}var em=new Set([".cmd",".bat"]),tm=new Set([".exe",".com"]),FT=new Set([...tm,...em]);var pt=require("fs"),Jc=me(require("path"),1);M();le();var rm=["CLAUDECODE_","CLAUDE_CODE_"],nm=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),sm=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),im=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...sm]);function Le(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(im.has(t)){e[t]=n;continue}nm.has(t)||rm.some(s=>t.startsWith(s))||(e[t]=n)}return e}W();var Vi=require("child_process"),Gc=require("fs");M();var om=5e3,Kc=new Map,zi=0;function zc(r,e,t){if(t.status!==0)return null;if(typeof t.stdout!="string")return f.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:r,status:t.status}),null;let n=t.stdout.trim();return n.length>0?n:null}function am(r){zi+=1;let e=(0,Vi.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Le(process.env),LC_ALL:"C",LANG:"C"}});return zc("powershell-cim",r,e)}function cm(r,e=!1){if(!e){let n=Kc.get(r);if(n&&(r===process.pid||Date.now()-n.capturedAtMs<om))return n.token}let t=null;try{t=am(r)}catch(n){f.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return(t!==null||r!==process.pid)&&Kc.set(r,{token:t,capturedAtMs:Date.now()}),t}function Vc(r,e){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux"){zi+=1;try{let t=(0,Gc.readFileSync)(`/proc/${r}/stat`,"utf-8"),n=t.lastIndexOf(") ");if(n<0)return null;let i=t.slice(n+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(t){return f.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}if(process.platform==="win32")return cm(r,e);zi+=1;try{let t=(0,Vi.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Le(process.env),LC_ALL:"C",LANG:"C"}});return zc("ps-lstart",r,t)}catch(t){return f.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}function Ne(r){return Vc(r,!1)}function Re(r,e){if(e===null)return!0;let t=Vc(r,!0);return t===null?!0:t===e}var qc=require("child_process"),In=require("fs"),Yc=require("util");M();var qi=(0,Yc.promisify)(qc.execFile),lm=128,um=/not found|no running instance|no tasks/i,On=class extends Error{pid;constructor(e,t,n){super(t,n),this.name="ProcessTreeKillError",this.pid=e}};async function he(r,e={}){let t=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Ne(r),s=()=>Re(r,n);if(!s()){f.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:r});return}if(f.debug("PROCESS",`Killing process tree rooted at PID ${r}`,{immediate:t}),process.platform==="win32"){try{await qi("taskkill",["/PID",String(r),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let o=i.code,a=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(o===lm||um.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:r});return}throw new On(r,`taskkill failed for PID ${r} (exit ${String(o)}): ${a.trim()||c}`,{cause:i})}return}try{let i=t?"SIGKILL":"SIGTERM",o=await Cn(r);for(let l of o){if(!Re(l.pid,l.startToken)){f.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:r});continue}try{process.kill(l.pid,i)}catch{}}if(s())try{process.kill(r,i)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&f.debug("PROCESS",`Failed to ${i} PID ${r}`,{code:d},u)}else f.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:r,signal:i});t||await new Promise(l=>setTimeout(l,500));let a=s()?await Cn(r):[],c=new Map;for(let l of o)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!Re(l,u)){f.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:r});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!t&&s())try{process.kill(r,"SIGKILL")}catch{}}catch(i){throw new On(r,`tree-kill failed for PID ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function dm(){return process.platform==="win32"?gm():process.platform==="linux"?fm():pm()}function fm(){let r=[],e;try{e=(0,In.readdirSync)("/proc")}catch(t){return f.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),r}for(let t of e){if(!/^\d+$/.test(t))continue;let n;try{n=(0,In.readFileSync)(`/proc/${t}/stat`,"utf-8")}catch{continue}let s=n.lastIndexOf(") ");if(s<0)continue;let i=n.slice(s+2).split(" "),o=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(o)&&r.push({pid:Number.parseInt(t,10),ppid:o,startToken:a&&/^\d+$/.test(a)?a:null})}return r}async function pm(){let r;try{r=(await qi("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(t){return f.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(`
17
- `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function gm(){let r;try{r=(await qi("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(t){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(/\r?\n/).slice(1)){let n=t.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 Cn(r){let e=await dm(),t=new Map;for(let o of e){let a=t.get(o.ppid);a?a.push(o):t.set(o.ppid,[o])}let n=new Set([r]),s=[],i=o=>{for(let a of t.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(r),s}var hm=5e3,_m=1e3,Em=j.supervisorRegistry(),Sm=null;function J(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Pn(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!J(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Xc(r){if(!r||!J(r.pid))return!1;if(!r.startToken)return!0;let e=Ne(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ym={platform:process.platform,readCommandLine:r=>(0,pt.readFileSync)(`/proc/${r}/cmdline`,"utf-8")};function kn(r,e=ym){if(!Xc(r))return!1;if(r.startToken||e.platform!=="linux")return!0;let t;try{t=e.readCommandLine(r.pid)}catch(s){return f.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:r.pid,error:s instanceof Error?s.message:String(s)}),!0}let n=t.split("\0").some(s=>Jc.default.basename(s)==="worker-service.cjs");return n||f.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:r.pid}),n}function Qe(r=j.workerPid()){if(!(0,pt.existsSync)(r))return null;let e;try{e=JSON.parse((0,pt.readFileSync)(r,"utf-8"))}catch{return null}return e!==null&&kn(e)?e:null}var Xi=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Em){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,pt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,pt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(t){t instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,t){let n=this.entries.get(e);if(!n||n.pid===t||!J(n.pid))return;let s=`${e}#superseded:${n.pid}`;this.entries.set(s,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(s,i),this.runtimeProcesses.delete(e)),f.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:s,supersededPid:n.pid,incomingPid:t})}register(e,t,n){this.initialize(),this.retainSupersededEntry(e,t.pid),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,t){this.initialize();let n=e,s=this.entries.get(n);t!==void 0&&s?.pid!==t&&(n=`${e}#superseded:${t}`,s=this.entries.get(n),s?.pid!==t)||s&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),s?.type==="sdk"&&Ji())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),s=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,s]of this.entries)J(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)Ji();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let s=t.filter(a=>J(a.pid)),i=new Map(s.map(a=>[a.pid,Ne(a.pid)]));for(let a of s)try{process.platform==="win32"?await he(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Pn(s,hm);let o=s.filter(a=>J(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!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 he(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+_m;for(;Date.now()<a&&o.filter(l=>J(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&Ji();return f.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{K(this.registryPath,e),this.persistDegraded=!1}catch(t){this.reportPersistFailure(t)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let t=e instanceof Error?e:new Error(String(e));f.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},t);try{Sm?.({errorCategory:t.code??"unknown"})}catch{}}},Yi=null;function xn(){return Yi||(Yi=new Xi),Yi}var rA=180*1e3,bm=[];function Ji(){let r=bm.shift();r&&r.notify()}var Lt=require("fs");M();W();var wm=j.workerPid();async function Zc(r){let e=r.currentPid??process.pid,t=r.pidFilePath??wm,n=r.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!J(c.pid)){r.registry.unregister(c.id);continue}o.set(c.id,Ne(c.pid)),i.set(c.id,await Cn(c.pid));try{await Qc(c,"SIGTERM")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await Pn(s,5e3);let a=s.filter(c=>J(c.pid)||(i.get(c.id)??[]).some(l=>J(l.pid)));for(let c of a){let l=Re(c.pid,o.get(c.id)??null);l||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Qc(c,"SIGKILL")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{Tm(i.get(c.id)??[],c.pid)}}await Pn(a,1e3);for(let c of s)r.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))r.registry.unregister(c.id);el(t,e),r.registry.pruneDeadEntries()}function el(r,e,t=!1){if(!(0,Lt.existsSync)(r))return;let n=null;try{let o=JSON.parse((0,Lt.readFileSync)(r,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!J(n);if(!s&&!(t&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,Lt.rmSync)(r,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(o)})}}function Tm(r,e){for(let{pid:t,startToken:n}of r)if(!(t===e||!J(t))){if(!Re(t,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:t,rootPid:e});continue}try{process.kill(t,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:t,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:t,rootPid:e,errno:i})}}}async function Qc(r,e){let{pid:t,pgid:n}=r;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 he(t,{signalMode:"immediate"});return}try{process.kill(t,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await he(t)}M();var tl=3e4,Nt=null;function Am(){let e=xn().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function rl(){Nt===null&&(Nt=setInterval(Am,tl),Nt.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:tl}))}function nl(){Nt!==null&&(clearInterval(Nt),Nt=null,f.debug("SYSTEM","Health checker stopped"))}var sl=require("child_process"),il=require("util");M();var Rm=(0,il.promisify)(sl.execFile),vm=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Mm(r){let e=[];for(let t of r.split(`
17
+ `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function gm(){let r;try{r=(await qi("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(t){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(/\r?\n/).slice(1)){let n=t.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 Cn(r){let e=await dm(),t=new Map;for(let o of e){let a=t.get(o.ppid);a?a.push(o):t.set(o.ppid,[o])}let n=new Set([r]),s=[],i=o=>{for(let a of t.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(r),s}var hm=5e3,_m=1e3,Em=j.supervisorRegistry(),Sm=null;function J(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Pn(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!J(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Xc(r){if(!r||!J(r.pid))return!1;if(!r.startToken)return!0;let e=Ne(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ym={platform:process.platform,readCommandLine:r=>(0,pt.readFileSync)(`/proc/${r}/cmdline`,"utf-8")};function kn(r,e=ym){if(!Xc(r))return!1;if(r.startToken||e.platform!=="linux")return!0;let t;try{t=e.readCommandLine(r.pid)}catch(s){return f.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:r.pid,error:s instanceof Error?s.message:String(s)}),!0}let n=t.split("\0").some(s=>Jc.default.basename(s)==="worker-service.cjs");return n||f.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:r.pid}),n}function Qe(r=j.workerPid()){if(!(0,pt.existsSync)(r))return null;let e;try{e=JSON.parse((0,pt.readFileSync)(r,"utf-8"))}catch{return null}return e!==null&&kn(e)?e:null}var Xi=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Em){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,pt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,pt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(t){t instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,t){let n=this.entries.get(e);if(!n||n.pid===t||!J(n.pid))return;let s=`${e}#superseded:${n.pid}`;this.entries.set(s,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(s,i),this.runtimeProcesses.delete(e)),f.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:s,supersededPid:n.pid,incomingPid:t})}register(e,t,n){this.initialize(),this.retainSupersededEntry(e,t.pid),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,t){this.initialize();let n=e,s=this.entries.get(n);t!==void 0&&s?.pid!==t&&(n=`${e}#superseded:${t}`,s=this.entries.get(n),s?.pid!==t)||s&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),s?.type==="sdk"&&Ji())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),s=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,s]of this.entries)J(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)Ji();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let s=t.filter(a=>J(a.pid)),i=new Map(s.map(a=>[a.pid,Ne(a.pid)]));for(let a of s)try{process.platform==="win32"?await he(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Pn(s,hm);let o=s.filter(a=>J(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!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 he(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+_m;for(;Date.now()<a&&o.filter(l=>J(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&Ji();return f.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{K(this.registryPath,e),this.persistDegraded=!1}catch(t){this.reportPersistFailure(t)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let t=e instanceof Error?e:new Error(String(e));f.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},t);try{Sm?.({errorCategory:t.code??"unknown"})}catch{}}},Yi=null;function xn(){return Yi||(Yi=new Xi),Yi}var rA=180*1e3,bm=[];function Ji(){let r=bm.shift();r&&r.notify()}var Nt=require("fs");M();W();var wm=j.workerPid();async function Zc(r){let e=r.currentPid??process.pid,t=r.pidFilePath??wm,n=r.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!J(c.pid)){r.registry.unregister(c.id);continue}o.set(c.id,Ne(c.pid)),i.set(c.id,await Cn(c.pid));try{await Qc(c,"SIGTERM")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await Pn(s,5e3);let a=s.filter(c=>J(c.pid)||(i.get(c.id)??[]).some(l=>J(l.pid)));for(let c of a){let l=Re(c.pid,o.get(c.id)??null);l||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Qc(c,"SIGKILL")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{Tm(i.get(c.id)??[],c.pid)}}await Pn(a,1e3);for(let c of s)r.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))r.registry.unregister(c.id);el(t,e),r.registry.pruneDeadEntries()}function el(r,e,t=!1){if(!(0,Nt.existsSync)(r))return;let n=null;try{let o=JSON.parse((0,Nt.readFileSync)(r,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!J(n);if(!s&&!(t&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,Nt.rmSync)(r,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(o)})}}function Tm(r,e){for(let{pid:t,startToken:n}of r)if(!(t===e||!J(t))){if(!Re(t,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:t,rootPid:e});continue}try{process.kill(t,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:t,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:t,rootPid:e,errno:i})}}}async function Qc(r,e){let{pid:t,pgid:n}=r;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 he(t,{signalMode:"immediate"});return}try{process.kill(t,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await he(t)}M();var tl=3e4,Ft=null;function Am(){let e=xn().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function rl(){Ft===null&&(Ft=setInterval(Am,tl),Ft.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:tl}))}function nl(){Ft!==null&&(clearInterval(Ft),Ft=null,f.debug("SYSTEM","Health checker stopped"))}var sl=require("child_process"),il=require("util");M();var Rm=(0,il.promisify)(sl.execFile),vm=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Mm(r){let e=[];for(let t of r.split(`
18
18
  `)){let n=t.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 Om(){let r=await Rm("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Mm(r.stdout)}function Cm(r,e){let t=r.filter(o=>vm.test(o.command)&&o.pid!==e.selfPid),n=new Set(t.map(o=>o.pid)),s=t.filter(o=>!n.has(o.ppid)),i=s.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:t,roots:s,orphans:i}}async function ol(r={}){let e=r.platform??process.platform,t={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return t.skipped="windows",t;let n=r.readTable??Om,s=r.isAlive??J,i=r.killTree??(p=>he(p,{signalMode:"graceful"})),o=r.selfPid??process.pid,a;try{a=await n()}catch(p){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),t.skipped="unreadable",t}let{matched:c,roots:l,orphans:u}=Cm(a,{isAlive:s,selfPid:o});if(t.matched=c.length,t.trees=l.length,t.orphans=u.length,u.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:t.matched,trees:t.trees}),t;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(p=>p.pid)});let d=new Set,g=8;for(let p=0;p<u.length;p+=g){let m=u.slice(p,p+g);(await Promise.allSettled(m.map(_=>i(_.pid)))).forEach((_,E)=>{let y=m[E];_.status==="fulfilled"?(t.killed+=1,d.add(y.pid)):(t.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:y.pid,ppid:y.ppid,error:_.reason instanceof Error?_.reason.message:String(_.reason)}))})}if(r.registry)for(let p of r.registry.getAll())p.type==="chroma"&&d.has(p.pid)&&(r.registry.unregister(p.id),t.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:t.orphans,killed:t.killed,failed:t.failed,unregistered:t.unregistered}),t}W();var Im=j.workerPid(),Qi=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(),al({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ol({registry:this.registry}).catch(t=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:t instanceof Error?t.message:String(t)})}),rl()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=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(i){i instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}nl(),this.stopPromise=Zc({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e,t){this.registry.unregister(e,t)}getRegistry(){return this.registry}},wA=new Qi(xn());function al(r={}){let e=r.pidFilePath??Im;if(!(0,gt.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,gt.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,gt.rmSync)(e,{force:!0}),"invalid"}return kn(t)&&t?((r.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(r.removeStale===!1||(f.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,gt.rmSync)(e,{force:!0})),"stale")}_n();var Zi=require("path"),Ln=require("fs"),ll=require("crypto");W();var Dn=require("fs");le();function cl(r,e){if(!(0,Dn.existsSync)(r))return e;try{return cr((0,Dn.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}M();var ul="telemetry.json";function Pm(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function km(r,e){if(Pm(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Nn(r,e){return km(r,e).enabled}function dl(r){let e=r.CLAUDE_MEM_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function xm(){return(0,Zi.join)(re(),ul)}function hr(){let r;try{r=cl(xm(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function Dm(r){let e=re();(0,Ln.mkdirSync)(e,{recursive:!0}),(0,Ln.writeFileSync)((0,Zi.join)(e,ul),JSON.stringify(r,null,2)+`
19
19
  `)}function Fn(){let r=hr();if(r?.installId)return r.installId;let e=(0,ll.randomUUID)();return Dm({installId:e,decidedAt:""}),e}var gl=me(require("os"),1);M();var fl=500;var pl=8192,_e="[REDACTED]";function ml(r){try{if(typeof r!="string"){if(r==null)return"";try{r=String(r)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let e=r;return e.length>pl?e.slice(0,pl):e}catch{return""}}function eo(r){if(typeof r!="string"||r.length===0)return r??"";let e="";try{e=gl.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 r;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return r.replace(new RegExp(t,"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),r.split(e).join("~")}}function to(r){return typeof r!="string"||r.length===0?r??"":r.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function Lm(r){return typeof r!="string"||r.length===0?r??"":r.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${_e}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${_e}@`))}function Nm(r){return typeof r!="string"||r.length===0?r??"":r.replace(/\?[^\s"'()]*/g,"")}function Fm(r){return typeof r!="string"||r.length===0?r??"":r.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let t=e.indexOf("=");return`${e.slice(0,t+1)}${_e}`})}function Um(r){if(typeof r!="string"||r.length===0)return r??"";let e=r;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,_e),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,_e),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,_e),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,_e),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,_e),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,_e),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,_e),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,_e),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,_e),e}function $m(r){return typeof r!="string"||r.length===0?r??"":r.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
20
- `).trim()}function ro(r){let e=ml(r);return e.length===0?"":(e=eo(e),e=Lm(e),e=to(e),e=Nm(e),e=Fm(e),e=Um(e),e)}function hl(r){try{let e=$m(ro(ml(r)));return e.length>fl?e.slice(0,fl):e}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,t),""}}function _l(r){return(typeof r=="string"?r:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var Bm=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","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","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","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(r=>["read","write"].flatMap(e=>[`${r}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(t=>`${r}_${e}_${t}_count`)]))]),El=200;function Wm(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Bm.has(t))continue;let n=r[t];if(typeof n=="string"){let s=n.length>El?n.slice(0,El):n;e[t]=ro(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Un(r){let e={};try{Wm(r,e)}catch{}return e}var no=me(require("os"),1);M();var Hm="13.41.0",jm="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Km="https://us.i.posthog.com";function $n(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||jm}function Bn(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Km}var Gm=["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"];function Wn(r){let e={};for(let t of Gm)r[t]!==void 0&&(e[t]=r[t]);return e}function zm(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||no.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Hn(){return{version:Hm,os:process.platform,os_version:no.default.release(),is_wsl:zm(),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 Vm=2e3;async function Sl(r,e,t){try{if(!Nn(process.env,hr()))return;let n=Un({...Hn(),...e??{}});if(t?.person?n.$set=Wn(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
21
- `);return}let s=$n(),i=new AbortController,o=setTimeout(()=>i.abort(),Vm);try{await qm(s,r,n,i.signal)}finally{clearTimeout(o)}}catch{}}async function qm(r,e,t,n){await fetch(`${Bn()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Fn(),properties:t}),signal:n})}var ue=me(require("path"),1),go=require("os"),fe=require("fs"),qn=require("child_process");M();M();M();var oe=me(require("path"),1),Ft=require("fs"),Vn=require("os"),lo=require("child_process");lr();W();M();var jn=require("fs"),Ze=me(require("path"),1);M();var _r={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function yl(r){let e=Ze.default.join(r,".git"),t;try{t=(0,jn.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)}),_r}if(!t.isFile())return _r;let n;try{n=(0,jn.readFileSync)(e,"utf-8").trim()}catch(c){return f.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),_r}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return _r;let i=Ze.default.resolve(Ze.default.dirname(e),s[1]),o=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(o){let c=o[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Ze.default.basename(r),parentRepoPath:c,parentProjectName:Ze.default.basename(c)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Ze.default.basename(r),parentRepoPath:c,parentProjectName:Ze.default.basename(c)}}return _r}var Tl=require("fs");var so=require("path");lr();M();function bl(r){let e=Pe(r.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function wl(r,e,t){let n=bl(r);return n.test(e)||n.test(t)?!0:r.replace(/\\/g,"/").endsWith("/**")?bl(r.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function io(r,e){if(!e.length)return!1;let t=r.replace(/\\/g,"/"),n=(0,so.basename)(t);for(let s of e){let i=s.trim();if(i)try{if(wl(i,t,n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}}return!1}function Kn(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,so.basename)(t),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{if(wl(i,t,n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}M();function Al(r){let e=r;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return f.warn("PROJECT_NAME","CLAUDE_MEM_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","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let t=[];for(let n of e){let s=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(o=>typeof o=="string"&&o.trim()!==""):[];if(!s||i.length===0){f.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:s});continue}t.push({name:s,patterns:i})}return t}function Ym(r){try{return(0,Tl.realpathSync)(r)}catch{return r}}function oo(r,e){if(e.length===0)return null;let t=[...new Set([r,Ym(r)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(t.some(s=>io(s,n.patterns)))return n.name;return null}var uo="unknown-project";function Ml(r){try{return(0,lo.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:r},t),null}}var Jm=[".claude-mem-project",".claude-mem.json"],Xm=64;function Ol(r){try{return(0,Ft.realpathSync)(r)}catch{return r}}function Qm(r,e){let t=oe.default.relative(e,r);return t===""||!t.startsWith("..")&&!oe.default.isAbsolute(t)}function Zm(){return[(0,Vn.homedir)(),(0,Vn.tmpdir)(),ut].flatMap(r=>{let e=oe.default.resolve(r);return[e,Ol(e)]})}function Cl(r){let e=Zm(),t=oe.default.resolve(r);if([oe.default.resolve(ut),Ol(oe.default.resolve(ut))].some(s=>Qm(t,s)))return null;for(let s=0;s<Xm;s++){if(e.includes(t))return null;let i=oe.default.dirname(t);if(i===t)return null;if(Jm.some(o=>(0,Ft.existsSync)(oe.default.join(t,o))))return t;t=i}return null}function co(r,e){let t=oe.default.basename(e);if(t===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:o}),o}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),uo}return t}var eh="CLAUDE_MEM_PROJECT_NAME_SOURCE",Gn=null;function Rl(){try{return(0,Ft.statSync)(ne).mtimeMs}catch{return-1}}function Il(){let r=Rl();if(r===-1)return H.getAllDefaults();if(Gn&&Gn.mtimeMs===r)return Gn.settings;let e=H.loadFromFile(ne);return Gn={mtimeMs:Rl(),settings:e},e}function th(){let r=process.env[eh]??Il().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(r??"path").trim().toLowerCase()==="git-remote"}var rh="CLAUDE_MEM_PROJECT_ENVIRONMENTS",zn=null;function Pl(){let r=process.env[rh]??Il().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!zn||zn.raw!==r)&&(zn={raw:r,environments:Al(r)}),zn.environments}function nh(r){let e=(r??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),s=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=s?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),o=s?.[1]??i?.[1];if(!o)return null;let a=o.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function sh(r){try{let e=(0,lo.execFileSync)("git",["remote","get-url","origin"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return nh(e)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:r},t),null}}var ao=new Map;function kl(r){return th()?(ao.has(r)||ao.set(r,sh(r)),ao.get(r)??null):null}function ih(r,e=process.platform){if(!r||r.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),uo;let t=Pe(r,e),n=oo(t,Pl());if(n)return n;let s=Ml(t),i=s?kl(s):null;if(i)return i;let o=s??Cl(t)??t;return co(r,o)}function xl(r,e){return e===r?r:`${r}/${e}`}function oh(r,e){if(!r.isSubmodule||!r.parentRepoPath)return null;let t=oe.default.relative(r.parentRepoPath,e);return!t||t.startsWith("..")||oe.default.isAbsolute(t)?null:t.split(oe.default.sep).join("/")}function mt(r,e=process.platform){if(!r||r.trim()===""){let c=ih(r,e);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let t=Pe(r,e),n=Ml(t),s=ah(r,t,n),i=n?kl(n):null,o=i?vl(s,i,"git-remote"):s,a=oo(t,Pl());return a?vl(o,a,"environment"):o}function vl(r,e,t){return{primary:e,parent:null,isWorktree:r.isWorktree,isSubmodule:r.isSubmodule,allProjects:[...r.allProjects.filter(n=>n!==e),e],keySource:t}}function ah(r,e,t){let n=t?null:Cl(e),s=co(r,t??n??e),i=t??e,o=yl(i);if((o.isWorktree||o.isSubmodule)&&o.parentProjectName){let a=o.parentProjectName,c,l;return o.isSubmodule?(c=`${a}/${oh(o,i)??s}`,l=s!==a?[s]:[]):(c=xl(a,s),l=c===a?[`${a}/${s}`]:[]),{primary:c,parent:a,isWorktree:o.isWorktree,isSubmodule:o.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(u=>u!==c).concat(c),keySource:"path"}}if(n&&oe.default.resolve(n)!==oe.default.resolve(e)){let a=co(r,e);if(a!==s&&a!==uo)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"}}W();var Dl=xe(Q.POWERSHELL_COMMAND);function lh(r){return r===void 0?Dl:Math.max(1,Math.min(Dl,r))}var wR=j.dataDir(),TR=j.workerPid(),uh="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite.";function dh(r){try{return(0,fe.realpathSync)(r)}catch{return null}}function fo(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function fh(r,e){let t=e==="win32"?"where.exe":"which",n=[r],s;try{s=(0,qn.execFileSync)(t,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t,args:n},o):f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t,args:n},new Error(String(o))),null}return s.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}var po;function mo(r={}){let e=Object.keys(r).length===0;if(e&&po!==void 0)return po;let t=ph(r);return e&&t!==null&&(po=t),t}function Ll(r,e){let t=r?.trim();return t?e==="win32"?[ue.default.join(t,"bin","bun.exe"),ue.default.join(t,"bin","bun"),ue.default.join(t,"bun.exe")]:[ue.default.join(t,"bin","bun"),ue.default.join(t,"bun")]:[]}function ph(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(fo(t))return t;let n=r.env??process.env,s=r.homeDirectory??(0,go.homedir)(),i=r.pathExists??fe.existsSync,o=r.lookupInPath??fh,a=r.realpath??dh,c=e==="win32"?[n.BUN,n.BUN_PATH,...Ll(n.BUN_INSTALL,e),ue.default.join(s,".bun","bin","bun.exe"),ue.default.join(s,".bun","bin","bun"),n.USERPROFILE?ue.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?ue.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?ue.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?ue.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...Ll(n.BUN_INSTALL,e),ue.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?ue.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let g=d?.trim();if(g&&(fo(g)&&i(g)||g.toLowerCase()==="bun"))return g}let l=o("bun",e)?.trim();if(!l||!fo(l))return null;let u=a(l)??l;return i(u)?u:null}function ho(){let r=j.dataDir();return(0,fe.mkdirSync)(r,{recursive:!0}),r}function gh(r,e,t=ho()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(r)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(t)}' -WindowStyle Hidden`}function mh(r=process.env){let e=r.SystemRoot||r.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function hh(r,e,t=ho()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(gh(r,e,t),"utf16le").toString("base64")]}function _o(r,e,t,n=process.platform,s){if(n==="win32"){let u=mh(t),d=hh(r,e),g=lh(s);try{let p=(0,qn.spawnSync)(u,d,{stdio:"ignore",windowsHide:!0,env:t,timeout:g,killSignal:"SIGTERM"});if(p.error)throw p.error;if(p.signal)throw new Error(`powershell Start-Process killed by signal=${p.signal} after ${g}ms`);if(p.status!==0)throw new Error(`powershell Start-Process exited ${p.status??"null"}`);return 0}catch(p){let m=p instanceof Error?p:new Error(String(p));f.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:r,powershell:u},m);return}}let i="/usr/bin/setsid",o=(0,fe.existsSync)(i),a=o?i:r,l=Gi(a,o?[r,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:ho(),env:t});if(l.on("error",u=>{f.error("SYSTEM",uh,{runtimePath:r,execPath:a},u)}),l.pid!==void 0)return l.unref(),l.pid}var Fl=me(require("net"),1);M();W();function Nl(r){let e=r?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Eo="Set CLAUDE_MEM_WORKER_PORT to a port between 1024 and 65535 and CLAUDE_MEM_WORKER_HOST to an address of this machine (127.0.0.1 by default) in claude-mem settings";function So(){return H.loadFromFile(ne).CLAUDE_MEM_WORKER_HOST}function Ul(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}var ht=5e3;async function $l(r,e,t="GET",n=ht){let s=await fetch(`http://${Ul(So())}:${r}${e}`,{method:t,signal:AbortSignal.timeout(Math.max(1,n))}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}async function Bl(r,e=ht){let t=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${Ul(So())}:${r}/api/health`,{signal:AbortSignal.timeout(Math.max(1,t-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:r,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,error:String(s)})}let n=await Yn(r,Math.max(1,t-Date.now()));return n==="occupied"||n==="indeterminate"}async function Yn(r,e=ht){return(await _h(r,e)).occupancy}function _h(r,e=ht){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(t=>{let n=!1,s=!1,i=!1,o;try{o=Fl.default.createServer()}catch{t({occupancy:"indeterminate"});return}let a=u=>{if(i){u?.();return}i=!0;try{o.close(u)}catch(d){u?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(s)a();else try{o.close()}catch{}l({occupancy:"indeterminate"})},e),l=u=>{n||(n=!0,clearTimeout(c),t(u))};o.once("error",u=>{if(s)a();else try{o.close()}catch{}u.code==="EADDRINUSE"?l({occupancy:"occupied"}):Nl(u)?l({occupancy:"unbindable",bindErrorCode:u.code}):l({occupancy:"indeterminate"})}),o.once("listening",()=>{if(s=!0,n){a();return}try{a(u=>l({occupancy:u?"indeterminate":"free"}))}catch{l({occupancy:"indeterminate"})}});try{o.listen(r,So())}catch{try{o.close()}catch{}l({occupancy:"indeterminate"})}})}async function Eh(r,e,t,n){let s=Date.now()+t;for(;Date.now()<s;){try{let o=s-Date.now();if((await $l(r,e,"GET",Math.min(ht,o))).ok)return!0}catch(o){o instanceof Error?f.debug("SYSTEM",n,{},o):f.debug("SYSTEM",n,{error:String(o)})}let i=Math.min(500,s-Date.now());i>0&&await new Promise(o=>setTimeout(o,i))}return!1}function Wl(r,e=3e4){return Eh(r,"/api/health",e,"Service not ready yet, will retry")}async function Sh(r,e=ht){try{let t=await $l(r,"/api/health","GET",e);return t.ok?JSON.parse(t.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Hl(r,e,t=ht){let n=e??"unknown",s=await Sh(r,t);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}M();var Jn=require("path"),Z=require("fs");W();M();var Kl=9e4,HR=Kl/3;function Gl(){return(0,Jn.join)(re(),"spawn.lock")}function jl(r){try{let e=JSON.parse((0,Z.readFileSync)(r,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function yh(r){if(r===null)return null;try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}function yo(){let r=Gl(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,Z.mkdirSync)((0,Jn.dirname)(r),{recursive:!0}),(0,Z.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},s),!0;if(t>0)return!1;let o;try{o=(0,Z.statSync)(r).mtimeMs}catch{continue}let a=jl(r),c=null;if(a===null)try{c=(0,Z.readFileSync)(r,"utf-8")}catch{continue}if(Date.now()-o<=Kl&&yh(a)!==!1)return!1;let u;try{u=(0,Z.statSync)(r).mtimeMs}catch{continue}if(u!==o)return!1;if(a!==null){if(jl(r)!==a)return!1}else try{if((0,Z.readFileSync)(r,"utf-8")!==c)return!1}catch{continue}try{(0,Z.unlinkSync)(r)}catch{return!1}}return!1}function bo(){let r=Gl();try{if(JSON.parse((0,Z.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,Z.unlinkSync)(r)}catch{}}var Yl=require("node:child_process"),Er=require("node:fs"),Jl=require("node:util");M();W();var Xn=(0,Jl.promisify)(Yl.execFile),bh=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function zl(r){return bh.test(r.trim())}function wh(r,e){if(!r)return!1;let t=r.toLowerCase().replace(/\\/g,"/"),n=t.indexOf("--data-dir");if(n<0)return!1;let s=t.slice(n+10).trim();if(s.startsWith('"')){let o=s.indexOf('"',1);s=o<0?s.slice(1):s.slice(1,o)}let i=e.toLowerCase().replace(/\\/g,"/");return s===i||s.startsWith(i)&&s[i.length]==="/"}function Qn(r,e){return e===void 0?r:Math.max(1,Math.min(r,e))}async function Th(r){try{let e=await Xn("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:Qn(3e4,r),windowsHide:!0,maxBuffer:33554432}),t=JSON.parse(e.stdout),n=Array.isArray(t)?t:t===null?[]:[t],s=[];for(let i of n){let o=typeof i.Name=="string"?i.Name.trim():"";if(!o)continue;let a=typeof i.ProcessId=="number"?i.ProcessId:Number.parseInt(String(i.ProcessId),10),c=typeof i.ParentProcessId=="number"?i.ParentProcessId:Number.parseInt(String(i.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||s.push({pid:a,ppid:c,name:o,cmdline:typeof i.CommandLine=="string"?i.CommandLine:null,startToken:typeof i.StartToken=="string"&&i.StartToken.length>0?i.StartToken:null})}return s}catch(e){return f.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function Ah(r,e){try{let t=await Xn("netstat",["-ano"],{timeout:Qn(15e3,e),windowsHide:!0,maxBuffer:16777216});return Oh(t.stdout,r)}catch(t){return f.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:r,error:t instanceof Error?t.message:String(t)}),null}}async function Rh(r,e){try{let t=await Xn("lsof",["-nP",`-iTCP:${r}`,"-sTCP:LISTEN","-t"],{timeout:Qn(1e4,e),maxBuffer:1048576});return vh(t.stdout)}catch(t){let n=t;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(f.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:r,error:t instanceof Error?t.message:String(t)}),null)}}function vh(r){let e=new Set;for(let t of r.split(/\r?\n/)){let n=Number.parseInt(t.trim(),10);Number.isInteger(n)&&n>0&&e.add(n)}return[...e]}async function Mh(r,e){try{let n=(await Xn("ps",["-p",String(r),"-o","command="],{timeout:Qn(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function Oh(r,e){let t=new Set,n=`:${e}`;for(let s of r.split(/\r?\n/)){let i=s.trim();if(!/^TCP\b/i.test(i))continue;let o=i.split(/\s+/);if(!o[1]?.endsWith(n)||o[3]!=="LISTENING")continue;let c=Number.parseInt(o[4]??"",10);Number.isInteger(c)&&c>0&&t.add(c)}return[...t]}var Ch=/worker-service/i,Xl=1500,Ql=1e3,wo=5500,Vl=2*Xl+Ql+wo;async function Ih(r,e){let t=e.readOwnedWorker();if(t===null||t.port!==r)return null;let n=(u,d={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:r,pid:t.pid,reason:u,...d}),{reclaimed:!1,reason:u,killedPids:[]}),s=(e.now()-Date.parse(t.startedAt))/1e3;if(!Number.isFinite(s)||s<e.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:s,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(Ql),await e.probeHealth(r))return n("owner-responding");let i=await e.listOwners(r);if(i===null)return n("netstat-unreadable");if(!i.includes(t.pid))return f.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:r,pid:t.pid,listeners:i}),null;let o=e.readHeartbeat();if(o!==null&&o.pid===t.pid){let u=e.now(),d=Math.max(0,u-o.beatAtMs),g=Math.max(0,u-o.lastResponseAtMs);if(d<e.heartbeatStaleMs){if(g<e.maxSilentProtectionMs)return n("owner-progressing",{heartbeatAgeMs:Math.round(d),sinceLastResponseMs:Math.round(g)});f.warn("PROCESS","Worker finished no response within the protection window despite a fresh liveness heartbeat",{port:r,pid:t.pid,sinceLastResponseMs:Math.round(g),maxSilentProtectionMs:e.maxSilentProtectionMs})}}let a=await e.readIdentity(t.pid),c=t.startToken!==void 0&&a.startToken!==null&&a.startToken!==t.startToken;if(c||a.cmdline===null||!Ch.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:r,pid:t.pid,ageSeconds:Math.round(s)});try{await e.killTree(t.pid,{expectedStartToken:a.startToken??t.startToken??void 0,signalMode:"graceful"})}catch(u){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:r,pid:t.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let l=await e.listOwners(r);return l!==null&&l.length===0?(f.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:r,killedPids:[t.pid]}),{reclaimed:!0,killedPids:[t.pid]}):(f.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:r,pid:t.pid,stillOwnedBy:l}),{reclaimed:!1,reason:"still-bound",killedPids:[t.pid]})}async function Ph(r,e,t,n){let s=Ne(r),i=e?(await t(n))?.find(o=>o.pid===r)?.cmdline??null:await Mh(r,n);return Re(r,s)?{startToken:s,cmdline:i}:{startToken:null,cmdline:null}}async function Zl(r,e={}){let t=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,i=b=>s!==null&&s-n()<b,o=()=>s===null?void 0:Math.max(1,s-n());if(i(Vl))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:r,remainingMs:o(),neededMs:Vl}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((b,C)=>t()?Ah(b,C):Rh(b,C)),c=b=>a(b,o()),l=e.readTable??Th,u=()=>l(o()),d=e.killTree??((b,C)=>he(b,C)),g=e.dataDir??(()=>U),p=e.readIdentity??((b,C)=>Ph(b,t(),l,C)),m=await Ih(r,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??Qe,probeHealth:e.probeHealth??(b=>Wl(b,Xl)),readIdentity:b=>p(b,o()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??wc(),readHeartbeat:e.readHeartbeat??(()=>Lh()),heartbeatStaleMs:e.heartbeatStaleMs??xh(),maxSilentProtectionMs:e.maxSilentProtectionMs??Dh,now:n,sleep:e.sleep??(b=>new Promise(C=>setTimeout(C,b))),hasKillBudget:()=>!i(wo)});if(m!==null)return m;if(!t())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await c(r);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let _=await u();if(_===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(b=>J(b)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let y=new Map;for(let b of _){let C=y.get(b.ppid);C?C.push(b):y.set(b.ppid,[b])}let w=new Map,R=new Set,P=b=>{for(let C of y.get(b)??[])R.has(C.pid)||(R.add(C.pid),P(C.pid),zl(C.name)&&w.set(C.pid,C))};for(let b of h)P(b);let O=g();if(O)for(let b of _)w.has(b.pid)||zl(b.name)&&wh(b.cmdline,O)&&w.set(b.pid,b);if(w.size===0)return f.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:r,deadOwners:h,processTableRows:_.length,dataDir:O??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};f.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:r,deadOwners:h,targets:[...w.values()].map(b=>({pid:b.pid,name:b.name}))});let S=[];for(let b of w.values()){if(i(wo))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:r,killedPids:S}),{reclaimed:!1,reason:"out-of-budget",killedPids:S};try{await d(b.pid,{expectedStartToken:b.startToken,signalMode:"immediate"}),S.push(b.pid)}catch(C){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:r,pid:b.pid},C instanceof Error?C:new Error(String(C))),{reclaimed:!1,reason:"kill-failed",killedPids:S}}}let T=await c(r);return T!==null&&T.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:r,killedPids:S}),{reclaimed:!0,killedPids:S}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:r,killedPids:S,stillOwnedBy:T}),{reclaimed:!1,reason:"still-bound",killedPids:S})}var kh=12e4,ql={min:1e4,max:36e5};function xh(r=process.env,e=ne){let t=r.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??H.loadFromFile(e,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,n=Number(t);return Number.isSafeInteger(n)&&n>=ql.min&&n<=ql.max?n:kh}var Dh=6e5;function Lh(r=j.workerHeartbeat()){try{let e=JSON.parse((0,Er.readFileSync)(r,"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}le();var Ut=require("fs"),tu=require("module"),et=me(require("path"),1),Nh=["zod/v3","zod/v4","zod/v4-mini"];function eu(r){try{return(0,Ut.realpathSync)(r)}catch{return r}}function Fh(r,e){let t=et.default.relative(e,r);return t!==""&&!t.startsWith("..")&&!et.default.isAbsolute(t)}function ru(r){let e;try{let s=JSON.parse((0,Ut.readFileSync)(et.default.join(r,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let t=et.default.join(r,"node_modules"),n=e.filter(s=>!(0,Ut.existsSync)(et.default.join(t,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,tu.createRequire)(et.default.join(t,"noop.js")),i=eu(et.default.join(t,"zod"));for(let o of Nh)try{let a=s.resolve(o,{paths:[t]});Fh(eu(a),i)||n.push(o)}catch{n.push(o)}}return n}function mu(r,e,t){let n=process.env[r];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=t.min&&s<=t.max)return s;f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var St=mu("CLAUDE_MEM_HEALTH_TIMEOUT_MS",xe(Q.HEALTH_CHECK),{min:500,max:3e5}),Sr=mu("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",xe(Q.HOOK_READINESS_WAIT),{min:0,max:3e5}),Uh=5e3,$h={min:500,max:3e5},Bh={min:500,max:Q.SESSION_INIT_REQUEST_MAX},Mo=100;function hu(r=process.env){let e=r.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="on"||t==="yes"}function Wh(r){return hu()?{...r,verbose:!0}:r}function Hh(r){let e={},t=r;for(let n=0;t&&n<4;n++){let s=n===0?"error":`cause${n}`;if(t instanceof Error){let i=t;e[s]={name:t.name,message:t.message,...i.code!==void 0?{code:i.code}:{}},t=t.cause;continue}e[s]=String(t);break}return e}function jh(r,e,t){let n=typeof e.method=="string"?e.method:"GET",s=Hh(t),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:r,method:n},i),je(`[claude-mem] fetch verbose: ${n} ${r} ${i}
22
- `)}async function Oo(r,e={}){let t=Wh(e);try{return await fetch(r,t)}catch(n){throw hu()&&jh(r,e,n),n}}async function Co(r,e={},t){try{return await Oo(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}function Kh(r,e){let t=new AbortController,n=null,s=null,i=null,o=!1,a=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{o=!0,a(),i!==null&&(clearTimeout(i),i=null)},l=d=>{o||(n=d,c(),t.abort(d))},u=()=>{o||(a(),s=setTimeout(()=>l(new Error(`Request timed out after ${r.idleTimeoutMs}ms idle`)),r.idleTimeoutMs))};if(r.absoluteCapMs!==void 0&&r.absoluteCapMs>0){let d=r.absoluteCapMs;i=setTimeout(()=>l(new Error(`Request timed out after ${d}ms`)),d)}return u(),{signal:e?AbortSignal.any([e,t.signal]):t.signal,touch:u,pause:a,dispose:c,translate:d=>n??d}}async function _u(r,e,t){let n=Kh(t,e.signal),s;try{s=await Oo(r,{...e,signal:n.signal})}catch(l){throw n.dispose(),n.translate(l)}n.touch();let i=s.body,o=i?i.getReader():null,a=!1;async function*c(){if(!o){a=!0,n.dispose();return}try{for(;;){n.touch();let l;try{l=await o.read()}catch(u){throw a=!0,n.translate(u)}if(l.done){a=!0;return}n.pause(),t.onChunk?.(l.value),yield l.value}}finally{n.dispose(),a||await o.cancel()}}return{status:s.status,statusText:s.statusText,ok:s.ok,headers:s.headers,chunks:c(),cancel:async()=>{n.dispose(),o&&!a&&(a=!0,await o.cancel())}}}async function Gh(r,e,t){let n=await _u(r,e,t),s=new TextDecoder,i="";for await(let o of n.chunks)i+=s.decode(o,{stream:!0});return i+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:i}}var To=null,Ao=null,Zn=null,es=null,ts=null;function nu(){return F.default.join(H.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Io(r={}){return r.readOnly?H.loadFromFile(nu(),!0,r):(Zn!==null||(Zn=H.loadFromFile(nu())),Zn)}function su(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function Eu(r,e,t){let n=process.env[r];if(n!==void 0){let o=su(n,t);return o!==null?o:(f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let s=Io()[r],i=su(s,t);return i!==null?i:(f.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:s,min:t.min,max:t.max}),e)}function Ee(r={}){if(!r.readOnly&&To!==null)return To;let e=parseInt(Io(r).CLAUDE_MEM_WORKER_PORT,10);return r.readOnly||(To=e),e}function br(r={}){if(!r.readOnly&&Ao!==null)return Ao;let e=Io(r).CLAUDE_MEM_WORKER_HOST;return r.readOnly||(Ao=e),e}function zh(){return es!==null||(es=Eu("CLAUDE_MEM_API_TIMEOUT_MS",xe(Q.API_REQUEST),$h)),es}function Su(){return ts!==null||(ts=Math.min(Eu("CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS",ur(),Bh),Tc())),ts}function Po(r){return r===null?null:Math.max(0,r-Date.now())}function ns(r){let e=Po(r);return e!==null&&e<Mo}function tt(r,e){let t=Po(e);return t===null?r:Math.max(1,Math.min(r,t))}function yu(r){return`http://${mr(br())}:${Ee()}${r}`}function Fe(r,e={}){let t=e.method??"GET",n=yu(r),s={method:t};if(e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return Gh(n,s,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(o=>new Response(o.text.length>0?o.text:null,{status:o.status,statusText:o.statusText,headers:o.headers}));let i=e.timeoutMs??zh();return i>0?Co(n,s,i):Oo(n,s)}async function Vh(r){return(await Fe("/api/health",{timeoutMs:r})).ok}async function iu(r=St){return(await Fe("/api/readiness",{timeoutMs:r})).ok}function bu(r){let e=(0,k.existsSync)(F.default.join(r,"plugin","scripts"))?F.default.join(r,"plugin"):r;return F.default.join(e,"scripts","worker-service.cjs")}function qh(r,e){let t=d=>{let g=d.split("-")[0].split(".");return[parseInt(g[0],10)||0,parseInt(g[1],10)||0,parseInt(g[2],10)||0]},[n,s,i]=t(r),[o,a,c]=t(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let l=r.includes("-")?1:0,u=e.includes("-")?1:0;return l!==u?l-u:r<e?1:r>e?-1:0}function Yh(r=F.default.join(F.default.dirname(F.default.dirname(xt)),"cache","thedotmack","claude-mem")){try{return(0,k.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>F.default.join(r,e)).filter(e=>{try{if(!(0,k.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,k.existsSync)(F.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:bu(e),version:F.default.basename(e)}))}catch{return[]}}function ou(r){try{let e=JSON.parse((0,k.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function Jh(){return{cacheRoot:F.default.join(F.default.dirname(F.default.dirname(xt)),"cache","thedotmack","claude-mem"),marketplaceRoot:xt,cwd:process.cwd()}}function ko(r=Jh()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if((0,k.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let t=[...Yh(r.cacheRoot),{scriptPath:bu(F.default.join(r.marketplaceRoot,"plugin")),version:ou(F.default.join(r.marketplaceRoot,"package.json"))},{scriptPath:F.default.join(r.cwd,"plugin","scripts","worker-service.cjs"),version:ou(F.default.join(r.cwd,"package.json"))}];return Zh(t)}function Xh(r){return F.default.dirname(F.default.dirname(r))}function Qh(r){return ru(Xh(r.scriptPath)).length===0}function Zh(r,e=Qh){let t=r.filter(n=>(0,k.existsSync)(n.scriptPath));return t.length===0?null:(t.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:qh(n.version,s.version)),t.find(e)??t[0])}function xo(){return ko()?.scriptPath??null}async function e_(r){let e=r.deadlineAt??null,t=r.backoffMs;for(let n=1;n<=r.attempts;n++){if(ns(e))return!1;if(await Iu(e??Number.POSITIVE_INFINITY))return!0;n<r.attempts&&(await new Promise(s=>setTimeout(s,tt(t,e))),t*=2)}return!1}function au(r){return r instanceof Error&&/^Request timed out after \d+ms idle$/.test(r.message)}function cu(r){return r instanceof Error&&/^Request timed out after \d+ms$/.test(r.message)}async function t_(r){let e;try{e=await _u(yu("/api/ready"),{method:"GET"},{idleTimeoutMs:Uh,absoluteCapMs:Math.max(1,r)})}catch(i){return au(i)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:cu(i)?{outcome:"still_booting",detail:"budget spent before response headers"}:(f.debug("SYSTEM","Worker /api/ready connection failed",{error:i instanceof Error?i.message:String(i)}),{outcome:"not_running"})}let t=()=>e.cancel().catch(i=>{f.debug("SYSTEM","Releasing the /api/ready body failed",{error:i instanceof Error?i.message:String(i)})}),n=e.headers?.get("content-type")??"";if(!e.ok||!n.includes("text/event-stream"))return ss(),await t(),{outcome:"unsupported"};let s=null;try{for await(let i of jc(e.chunks)){if(i.event!=="phase")continue;let o=JSON.parse(i.data);if(s=typeof o.phase=="string"?o.phase:null,s==="ready")return ss(),await t(),{outcome:"ready"};if(s==="failed")return await t(),{outcome:"failed",detail:typeof o.message=="string"?o.message:"unknown init failure"}}}catch(i){return cu(i)?(ss(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):au(i)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${s??"none"})`}:{outcome:"wedged",detail:`stream error: ${i instanceof Error?i.message:String(i)} (last phase ${s??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${s??"none"})`}}async function r_(r){if(r<=0)try{return await iu()?{outcome:"ready"}:{outcome:"still_booting"}}catch(t){return f.debug("SYSTEM","Worker readiness check threw",{},t instanceof Error?t:new Error(String(t))),{outcome:"still_booting"}}let e=Date.now();do{let t=r-(Date.now()-e);try{if(await iu(Math.max(1,Math.min(St,t))))return{outcome:"ready"}}catch(s){f.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let n=r-(Date.now()-e);if(n<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,n)))}while(Date.now()-e<r);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function $t(r=Sr){let e=r>0?r:St,t=await t_(e);return t.outcome==="ready"&&l_(),t.outcome!=="unsupported"?t:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),r_(r))}async function n_(r=St){try{let t=await(await Fe("/api/health",{timeoutMs:r})).json();return typeof t.version=="string"?t.version:null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("SYSTEM","Worker health-version fetch failed",{},t),null}}async function s_(r=5e3){let e=Date.now()+r;for(;;){let t=e-Date.now();if(t<=0)return!1;if(await Yn(Ee(),Math.min(1e3,t))==="free")return!0;let n=Math.min(200,e-Date.now());n>0&&await new Promise(s=>setTimeout(s,n))}}function wu(r,e){if(!r)return null;try{let t=(0,k.statSync)(r.scriptPath);return JSON.stringify([r.scriptPath,e,t.size,t.mtimeMs,t.ctimeMs])}catch{return null}}function Tu(){return F.default.join(re(),"worker-version-recycle.json")}function i_(r,e){if(r===null||e===null)return!1;try{let t=JSON.parse((0,k.readFileSync)(Tu(),"utf-8"));return t?.buildKey===r&&t?.workerVersion===e}catch{return!1}}async function lu(r,e=null,t=St){let n=await n_(t);if(n!==null&&n!==r){if(e!==null)try{K(Tu(),{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:r,workerVersion:n})}}var Au=3e4;function Do(){return F.default.join(re(),"worker-unresponsive.json")}function o_(){try{let r=JSON.parse((0,k.readFileSync)(Do(),"utf-8"));return typeof r?.pid!="number"||typeof r?.firstUnresponsiveAtEpochMs!="number"?null:{pid:r.pid,firstUnresponsiveAtEpochMs:r.firstUnresponsiveAtEpochMs}}catch{return null}}function ss(){let r=Do();if((0,k.existsSync)(r))try{(0,k.unlinkSync)(r)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function a_(r=Date.now()){let e=Qe()?.pid??null;if(e===null)return!1;let t=o_();if(t!==null&&t.pid===e)return r-t.firstUnresponsiveAtEpochMs>=Au;try{K(Do(),{pid:e,firstUnresponsiveAtEpochMs:r})}catch(n){f.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function Lo(){return F.default.join(re(),"worker-never-ready-recycle.json")}function c_(){try{let r=JSON.parse((0,k.readFileSync)(Lo(),"utf-8"));return typeof r?.buildKey!="string"||typeof r?.failureMessage!="string"?null:{buildKey:r.buildKey,failureMessage:r.failureMessage,refusalLogged:r.refusalLogged===!0}}catch{return null}}function Ru(r){try{K(Lo(),r)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function l_(){let r=Lo();if((0,k.existsSync)(r))try{(0,k.unlinkSync)(r)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function vu(r){return wu(r,r?.version??"unknown")??"unresolved-worker-bundle"}function Mu(r){return r.outcome==="failed"?r.detail??"unknown init failure":r.outcome}function Ou(r,e){if(r.outcome==="unresponsive"&&!a_())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:r.detail,wedgedAfterMs:Au}),!1;let t=Mu(r),n=c_();return n!==null&&n.buildKey===e&&n.failureMessage===t?(n.refusalLogged?f.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:t}):(f.error("SYSTEM","Worker keeps failing to start the same way after a recycle; not recycling again. Run `npx claude-mem doctor` and check the worker logs",{outcome:r.outcome,failureMessage:t,logsDir:F.default.join(re(),"logs")}),Ru({...n,refusalLogged:!0})),!1):!0}function Cu(r,e){Ru({buildKey:e,failureMessage:Mu(r)}),ss()}async function Iu(r=Number.POSITIVE_INFINITY){let e=r-Date.now();if(e<=0)return!1;let t;try{t=await Vh(Math.min(St,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return t}async function Pu(r,e){let t=Qe();if(t===null||t.port!==Ee())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:Ee(),pidFilePid:t?.pid??null,pidFilePort:t?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await he(t.pid,{signalMode:"immediate"})}catch(n){return f.error("SYSTEM","Could not kill stale worker",{pid:t.pid,port:t.port},n instanceof Error?n:new Error(String(n))),!1}return await s_(tt(5e3,r))?!0:(e("stale port release")||(Et=Ee(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:t.pid,port:Ee(),fix:os})),!1)}async function is(r){let e=r===void 0?null:Date.now()+r,t=h=>ns(e)?(f.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:h,budgetMs:r}),!0):!1,n=()=>e===null?void 0:tt(St,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),i=ko(),o=null,a=null,c=!1,l=null,u=null,d=Mn(Y());if(t("health probe"))return!1;if(await Iu(s)){if(t("version probe"))return!1;let{matches:h,pluginVersion:_,workerVersion:E}=await Hl(Ee(),i?.version??null,n());if(_!=="unknown"&&(o=_),h){if(t("readiness wait"))return!1;let y=await $t(tt(Sr,e));if(y.outcome==="ready")return o!==null&&!ns(e)&&await lu(o,null,n()),!0;if(y.outcome==="still_booting"||y.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:y.outcome,detail:y.detail}),!1;if(d)return f.warn("SYSTEM","Worker will never become ready; CLAUDE_MEM_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:y.outcome,detail:y.detail}),!1;if(u=vu(i),!Ou(y,u))return!1;l=y,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:y.outcome,detail:y.detail,version:E})}else{if(d)return f.warn("SYSTEM","Worker version differs from the installed plugin; CLAUDE_MEM_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:_,workerVersion:E}),t("readiness wait")?!1:(await $t(tt(Sr,e))).outcome==="ready";if(a=wu(i,_),i_(a,E))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:_,workerVersion:E,scriptPath:i?.scriptPath}),t("readiness wait")?!1:(await $t(tt(Sr,e))).outcome==="ready";f.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:_,workerVersion:E})}if(!await Pu(e,t))return!1;l!==null&&u!==null&&Cu(l,u),c=!0}if(d)return f.debug("SYSTEM","Worker not running and CLAUDE_MEM_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let g=i?.scriptPath??null;if(t("lazy spawn"))return!1;let p=yo();try{if(p){if(!c&&!await u_(s,e))return!1;let _=mo();if(!_)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!g)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:_,scriptPath:g});try{if(_o(_,g,Le({...process.env,CLAUDE_MEM_WORKER_PORT:String(Ee())}),process.platform,Po(e)??void 0)===void 0)return!1}catch(E){return E instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:_,scriptPath:g},E):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:_,scriptPath:g,error:String(E)}),!1}}else f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await e_({attempts:6,backoffMs:500,deadlineAt:e}))return t("cold-boot port wait")||(f.warn("SYSTEM",p?"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)"),Qe()===null&&await Bl(Ee(),e===null?void 0:tt(5e3,e))&&(Et=Ee(),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:Et,fix:os}))),!1}finally{p&&bo()}if(t("readiness wait"))return!1;let m=await $t(tt(Sr,e));return m.outcome!=="ready"?(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:m.outcome,detail:m.detail}),!1):(o!==null&&!ns(e)&&await lu(o,a,n()),!0)}var os="Set CLAUDE_MEM_WORKER_PORT to a different port in claude-mem settings, or reboot to release the stuck port",Et=null,vo=null;async function u_(r,e){let t=Ee(),n=r-Date.now();if(n<=0)return!1;let s=await Yn(t,n);if(s==="free")return!0;if(s==="unbindable")return vo=t,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:t,host:br(),fix:Eo}),!1;if(s==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:t}),!1;let i=await Zl(t,{deadlineAt:e});return i.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:t,killedPids:i.killedPids}),!0):(Qe()===null&&(Et=t),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:t,reclaimReason:i.reason,...Et===t?{fix:os}:{}}),!1)}var rs=null;async function d_(r){return rs!==null||(rs=await is(r)),rs}async function f_(r){let e=Date.now()+r,t=()=>e-Date.now(),n=l=>t()>=Mo?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:l,budgetMs:r}),!0),s=await $t(Math.max(1,t()));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:r}),!1;if(!!Mn(Y()))return uu(e);let o=mo(),a=xo();if(!o||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let l=vu(ko());if(!Ou(s,l)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await Pu(e,n)))return!1;Cu(s,l)}let c=yo();try{return c&&_o(o,a,Le({...process.env,CLAUDE_MEM_WORKER_PORT:String(Ee())}),process.platform,Math.max(1,t()))===void 0?!1:await uu(e)}catch(l){return f.debug("SYSTEM","Bounded worker startup failed",{error:l instanceof Error?l.message:String(l)}),!1}finally{c&&bo()}}async function uu(r){for(;r-Date.now()>0;){let e=await $t(Math.max(1,r-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 t=Math.min(100,r-Date.now());t>0&&await new Promise(n=>setTimeout(n,t))}return!1}var p_=3,ku=20,xu=1e3,g_=10,Du=5e3,m_=Du+xu;function as(){return F.default.join(U,"state")}function Lu(){return F.default.join(as(),"hook-failures.json")}function Nu(){return F.default.join(as(),"hook-failures.lock")}async function No(r=xu){let e=as(),t=Nu(),n=(0,gu.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),i=Date.now()+r;for(;Date.now()<=i;)try{return(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(t,s,{flag:"wx"}),n}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=a.code;if(c!=="EEXIST")return f.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:t,code:c},a),null;let l;try{l=(0,k.statSync)(t).mtimeMs}catch{continue}if(Date.now()-l>Du){let u;try{u=(0,k.statSync)(t).mtimeMs}catch{continue}if(u===l)try{(0,k.unlinkSync)(t);continue}catch{}}await new Promise(u=>setTimeout(u,g_))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:t,waitMs:r}),null}function Fo(r){let e=Nu();try{if(JSON.parse((0,k.readFileSync)(e,"utf-8")).token!==r)return;(0,k.unlinkSync)(e)}catch{}}function h_(r){let e=JSON.parse(r);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(t=>typeof t=="string").slice(-ku):void 0}}function yr(){try{return h_((0,k.readFileSync)(Lu(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Uo(r){let e=as(),t=Lu(),n=`${t}.tmp`;try{return(0,k.existsSync)(e)||(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,k.renameSync)(n,t),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function __(){try{let e=Y().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return p_}var du=null;function Fu(r){let e=vo!==null?`The worker cannot bind port ${vo} on ${br()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Eo}.`:Et!==null?`Port ${Et} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${os}.`:"Run `npx claude-mem restart`; if it keeps failing, run `npx claude-mem doctor`.";return`claude-mem worker unreachable for ${r} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${e}`}var E_=!1,fu=!1;async function Ro(){if(E_){if(fu)return yr().consecutiveFailures;fu=!0}let r=await No();if(r===null)return yr().consecutiveFailures;let e,t=!1;try{let n=yr();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=__();t=e.consecutiveFailures>=s&&!e.thresholdTripped,t&&(e.thresholdTripped=!0);let i=Uo(e);t=t&&i}finally{Fo(r)}return t&&(await Sl("hook_failed",{...du!==null?{hook_type:du}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),je(`${Fu(e.consecutiveFailures)}
23
- `)),e.consecutiveFailures}async function Uu(r){if(!r)return null;let e=await No();if(e===null)return null;try{let t=yr(),n=t.notifiedSessionIds??[];return!t.thresholdTripped||n.includes(r)?null:Uo({...t,notifiedSessionIds:[...n,r].slice(-ku)})?Fu(t.consecutiveFailures):null}finally{Fo(e)}}async function pu(){let r=await No(m_);if(r!==null)try{let e=yr();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;Uo({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Fo(r)}}var _t=Symbol.for("claude-mem/worker-fallback");function $u(r){return typeof r=="object"&&r!==null&&r[_t]===!0}async function Bu(r,e,t,n={}){let s=Date.now(),i=n.workerStartupTimeoutMs!==void 0;if(!(i?await f_(n.workerStartupTimeoutMs):await d_(n.timeoutMs)))return Mn(Y())?{continue:!0,reason:"worker_autostart_disabled",[_t]:!0}:(i||await Ro(),{continue:!0,reason:"worker_unreachable",[_t]:!0});let a={method:e};if(t!==void 0&&(a.headers={"Content-Type":"application/json"},a.body=JSON.stringify(t)),n.timeoutMs!==void 0){let u=i?n.timeoutMs:n.timeoutMs-(Date.now()-s);if(u<Mo)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:r}),i||await Ro(),{continue:!0,reason:"worker_budget_exhausted",[_t]:!0};a.timeoutMs=u}let c;try{c=await Fe(r,a)}catch(u){if(!i)throw u;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:u instanceof Error?u.message:String(u)}),{continue:!0,reason:"worker_unreachable",[_t]:!0}}if(!c.ok){let u=await c.text().catch(()=>"");if(await pu(),c.status===429||c.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${r} returned ${c.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${c.status}`,[_t]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}let l;try{l=await c.text()}catch(u){return f.debug("SYSTEM","Worker response body could not be read; treating the worker as unreachable",{error:u instanceof Error?u.message:String(u)}),i||await Ro(),{continue:!0,reason:"worker_body_read_failed",[_t]:!0}}if(await pu(),l.length!==0)try{return JSON.parse(l)}catch{return l}}M();var Ue=require("path");W();var S_="plugins",y_="cache",b_="thedotmack",w_="claude-mem",T_="plugin",A_=(0,Ue.join)(ut,S_,y_,b_,w_),R_=(0,Ue.join)(xt,T_);function $o(r,e){let t=(0,Ue.normalize)(r),n=(0,Ue.normalize)(e);if(t===n)return!0;let s=(0,Ue.relative)(n,t);return s.length>0&&!s.startsWith("..")&&!(0,Ue.isAbsolute)(s)}function cs(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if($o(r,wn)||$o(r,A_)||$o(r,R_))return!1;let e=Y();return!Kn(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Wu="claude";function v_(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function V(r){if(!r)return Wu;let e=v_(r);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:Wu}var M_=new Set(["claude","codex","cursor","kimi","antigravity-cli","gemini","opencode","openclaw","omp","pi","qwen","windsurf"]);function wr(r){if(!r||r==="unknown")return"unknown";let e=V(r);return M_.has(e)?e:"other"}function ls(r){if(r==="TodoWrite"||r==="SetTodoList"||r==="update_plan"||r==="functions.update_plan")return"native_todo";let e=r.replace(/^mcp__[^_].*?__/,"");return e==="work_state_write"?"write":e==="work_state_read"?"read":null}function Bo(r,e){if(typeof e=="string"){if(e.length<=32768&&e.trimStart().startsWith("{"))try{return Bo(r,JSON.parse(e))}catch{}return Hu(r,e.slice(0,1500),!1)}if(!e||typeof e!="object")return"unknown";let t=e,n=typeof t.error=="string"?t.error.slice(0,1500):Array.isArray(t.content)?t.content.slice(0,5).filter(s=>s&&s.type==="text"&&typeof s.text=="string").map(s=>s.text.slice(0,300)).join(`
24
- `):"";return Hu(r,n,t.isError===!0||!!t.error)}function Hu(r,e,t){return e.includes("CLAUDE_MEM_WORK_STATE_ENABLED=false")?"disabled":e.startsWith("Not saved: this project is excluded")?"excluded":t||/^(?:Error:|Tool execution failed:|Error executing tool|(?:Worker|Server) request failed(?: \(HTTP \d+\))?\.)/.test(e)?"error":r==="write"?e.startsWith('Saved to "')?"ok":"unknown":r==="read"&&e?"ok":"unknown"}M();var fs=require("fs");M();W();le();var us=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,O_=`(?=${us}{8})${us}*[A-Za-z]${us}*`,ds=String.raw`(?:\\{0,3}["'])?`,Rr=String.raw`\s{0,8}`;function Wo(r){return new RegExp(`${r}${O_}`,"gi")}function ju(r){return`(?<=${r}${ds}${Rr}[=:]${Rr}${ds})`}var C_=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s{0,8}[=:]\s{0,8}['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],I_=[{name:"generic_password",regex:Wo(ju(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:Wo(ju(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:Wo(`(?<=\\bAuthorization${ds}${Rr}:${Rr}${ds}Bearer${Rr})`)}],P_=1024*1024,k_="<redacted type='oversize'/>";function zu(r,e){if(!e.enabled||r.length===0)return{redacted:r,counts:{},oversize:!1};if(r.length>P_)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:r.length}),{redacted:k_,counts:{oversize:1},oversize:!0};let t=new Set(e.disabledBuiltinPatterns??[]),n={},s=r,i=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){f.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{i.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){f.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let o=[...i,...C_,...e.genericEnabled?I_:[]];for(let a of o)t.has(a.name)||(a.regex.lastIndex=0,s=s.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function x_(r){if(!r||r.trim()==="")return[];try{let e=JSON.parse(r);return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"&&typeof t.regex=="string"):(f.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return f.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function D_(r){return{enabled:r.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(r.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:x_(r.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:r.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:r.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}var Tr=null,Ku=0,L_=5e3,Ar=null,Gu=!1,N_={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},F_=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function U_(r){if(!(0,fs.existsSync)(r))return null;try{return(0,fs.readFileSync)(r,"utf-8")}catch{return""}}function $_(r){if(r===null)return!1;try{let e=JSON.parse(xi(r));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function B_(r,e,t){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(Ar?.enabled===!0||F_.test(e))?t:(Gu||(Gu=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:r,using:Ar?.enabled?"the last configuration that loaded":"the built-in patterns"})),Ar?.enabled?Ar:N_)}function Vu(r=ne){let e=Date.now();if(Tr&&e-Ku<L_)return Tr;let t=H.loadFromFile(r),n=D_(t),s=n.enabled?null:U_(r);return $_(s)?Tr=B_(r,s,n):(Tr=n,Ar=n),Ku=e,Tr}var Fv=new RegExp(`^${us}{8,}$`);var Ho=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],W_=new Set(Ho),qu=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Yu=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;function H_(r){let e=Object.fromEntries(Ho.map(u=>[u,0]));if(!r.includes("<"))return{text:r,counts:e,total:0};let t=r.length,n=new Int32Array(t+1);n[t]=t;for(let u=t-1;u>=0;u--)n[u]=r.charCodeAt(u)===62?u:n[u+1];let s=new Map,i=[],o=0,a=0;for(;a<t;){if(r.charCodeAt(a)!==60){a+=1;continue}Yu.lastIndex=a;let u=Yu.exec(r);if(u){let g=u[1],p=s.get(g),m=p&&p.head<p.items.length?p.items[p.head]:void 0;m&&a>=m.attrEnd&&(p.head+=1,i.push([m.start,a+u[0].length]),e[g]+=1,o+=1),a+=u[0].length;continue}qu.lastIndex=a;let d=qu.exec(r);if(d&&W_.has(d[1])){let g=d[1],p=a+d[0].length,m={start:a,attrEnd:n[p]},h=s.get(g);h?h.items.push(m):s.set(g,{items:[m],head:0}),a=p;continue}a+=1}i.sort((u,d)=>u[0]-d[0]);let c="",l=0;for(let[u,d]of i)u>l&&(c+=r.slice(l,u)),d>l&&(l=d);return c+=r.slice(l),{text:c,counts:e,total:o}}var Ju=100;function j_(r){let{text:e,counts:t,total:n}=H_(r);return n>Ju&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:Ju,contentLength:r.length}),{stripped:zu(e.trim(),Vu()).redacted,counts:t}}function ps(r){return j_(r).stripped}var K_=new RegExp(`<(${Ho.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);function jo(r){let e=t=>typeof t=="string"?K_.test(t)?ps(t):t:Array.isArray(t)?t.map(e):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([n,s])=>[n,e(s)])):t;return e(r)}var G_=["task-notification"],z_=new RegExp(`^\\s*<(${G_.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),V_=256*1024;function Xu(r){return!r||r.length>V_?!1:z_.test(r)}var q_=[/^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 Qu(r){let e=r.trimStart();return q_.some(t=>t.test(e))}M();var Y_=xe(Q.API_REQUEST),Ge=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),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)}},ms=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=J_(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Y_}async startSession(e,t={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new Ge("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e,t={}){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=gs(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,t)}async getJobStatus(e){if(!e)throw new Ge("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:t,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:gs(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:gs(e.platformSource)}:{},...e.metadata!==void 0?{metadata:jo(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:gs(e.platformSource)}:{},...e.payload!==void 0?{payload:jo(e.payload)}:{}}}async request(e,t,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new Ge("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${t}`,o={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(o.body=JSON.stringify(n));let a=d=>{let g=d instanceof Error?d.message:String(d),p=/timed out|timeout/i.test(g)||d instanceof Error&&(d.name==="TimeoutError"||d.name==="AbortError");return new Ge(p?"timeout":"transport",`Server ${e} ${t} failed: ${g}`,{cause:d})},c,l=s.timeoutMs??this.timeoutMs;try{c=await Co(i,o,l)}catch(d){throw a(d)}if(!c.ok){let d=await c.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${t} returned ${c.status}: ${X_(d,200)}`,{status:c.status})}let u;try{u=await c.text()}catch(d){throw a(d)}if(!u||u.length===0)return{};try{return JSON.parse(u)}catch(d){let g=d instanceof Error?d:new Error(String(d));throw new Ge("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:g})}}};function hs(r){return r instanceof Ge}function J_(r){return r.replace(/\/+$/,"")}function gs(r){return typeof r=="string"?V(r):null}function X_(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Zu(){let e=(Y().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Q_(){let r=Y(),e=(...o)=>{for(let a of o){let c=(a??"").trim();if(c.length>0)return c}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),s=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new ms(i),projectId:s,serverBaseUrl:t}}function _s(){if(Zu()!=="server")return{runtime:"worker"};let r=Q_();return r||{runtime:"worker"}}function Es(r,e){f.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var Z_={executeWithWorkerFallback:Bu,getSessionInitRequestTimeoutMs:Su,isWorkerFallback:$u,consumeWorkerOutageNotice:Uu,loadFromFileOnce:Y,resolveRuntimeContext:_s,logServerFallback:Es,shouldTrackProject:cs,readHookEnvironment:()=>process.env},ve=Z_,eE=2,Ko=500,tE=2e3;var Ss=class extends Error{constructor(t){super(`session-init did not record the prompt (${t})`);this.reason=t;this.name="SessionPromptNotRecordedError"}reason};function rd(r){return sE.run(r,!0)}var rE=r=>r?r.replace(/\\/g,"/").includes("/.qwen/"):!1,nE=(r,e=process.env)=>r?e.QWEN_PROJECT_DIR?!0:rE(r):!1,sE={async run(r,e){let t=e?void 0:Date.now(),{sessionId:n,prompt:s,submittedPrompt:i}=r,o=r.cwd??process.cwd();if(!n)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};if(!ve.shouldTrackProject(o))return f.info("HOOK","Project excluded from tracking",{cwd:o}),{continue:!0,suppressOutput:!0};if(s&&Xu(s))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:s.slice(0,80)}),{continue:!0,suppressOutput:!0};if(s&&V(r.platform)==="codex"&&Qu(s))return f.debug("HOOK","session-init: skipping a Codex internal helper prompt",{reason:"internal_system_prompt",preview:s.slice(0,80)}),{continue:!0,suppressOutput:!0};if(i===null)return f.debug("HOOK","session-init: host reported no user-submitted text; not storing a prompt",{sessionId:n}),{continue:!0,suppressOutput:!0};if(i===void 0&&!s?.trim()&&nE(r.transcriptPath,ve.readHookEnvironment()))return f.debug("HOOK","session-init: Qwen send carried no submitted_prompt and no prompt text; not storing a prompt",{sessionId:n}),{continue:!0,suppressOutput:!0};let a=i??s,c=!a||!a.trim()?"[media prompt]":a,l=mt(o),u=l.primary,d=V(r.platform),g=ve.loadFromFileOnce(),p=String(g.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",m=ve.resolveRuntimeContext(),h=Date.now(),_=ve.getSessionInitRequestTimeoutMs();if(m.runtime==="server")try{return await iE(m,r,n,d,u,c,Math.max(Ko,Math.floor(_/eE))),{continue:!0,suppressOutput:!0}}catch(O){if(hs(O)&&O.isFallbackEligible())ve.logServerFallback(O.kind,{status:O.status,message:O.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:O instanceof Error?O.message:String(O)}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:n,project:u});let E=ed(h,_);if(E<Ko){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:n,project:u,remainingMs:E}),e)throw new Ss("budget_exhausted");return{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS}}let y=await ve.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:n,project:u,prompt:c,platformSource:d,telemetryPlatformSource:wr(r.platform),telemetryPromptEpochMs:t,agentId:r.agentId,agentType:r.agentType,cwd:o,projectKeySource:l.keySource},td(d,E));if(ve.isWorkerFallback(y)){if(e)throw new Ss("reason"in y?y.reason:"worker_fallback");let O=await ve.consumeWorkerOutageNotice(n);return{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS,...O?{systemMessage:O}:{}}}if(typeof y?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:n,project:u}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};let w=y.sessionDbId,R=y.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:w,promptNumber:R,skipped:y.skipped,contextInjected:y.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${n} | prompt#=${R} | sessionDbId=${w}`),y.skipped&&y.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${w} | promptNumber=${R} | skipped=true | reason=private`,{sessionId:w}),{continue:!0,suppressOutput:!0};let P="";if(p&&c&&c.length>=20&&c!=="[media prompt]"){let O=g.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",S=ed(h,_);if(S<Ko)f.warn("HOOK","session-init: skipping semantic injection because the prompt budget is spent",{contentSessionId:n,project:u,remainingMs:S});else{let T=await ve.executeWithWorkerFallback("/api/context/semantic","POST",{q:c,project:u,projects:l.allProjects,limit:O,format:g.CLAUDE_MEM_SEMANTIC_INJECT_FORMAT,platformSource:d},td(d,S));!ve.isWorkerFallback(T)&&T?.context&&(f.debug("HOOK",`Semantic injection: ${T.count} observations for prompt`,{sessionId:w,count:T.count}),P=T.context)}}return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${w} | promptNumber=${R} | project=${u}`,{sessionId:w}),P?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:P}}:{continue:!0,suppressOutput:!0}}};async function iE(r,e,t,n,s,i,o){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:i}},{timeoutMs:o}),f.info("HOOK","session-init: server session started",{contentSessionId:t,project:s})}function ed(r,e){return Math.max(0,e-(Date.now()-r))}function td(r,e){return r==="codex"?{workerStartupTimeoutMs:Q.POST_SPAWN_WAIT,timeoutMs:Math.min(tE,e)}:{timeoutMs:e}}var Bt=require("crypto"),L=require("fs"),pe=require("path");le();W();M();var oE=["observation","file_edit","summarize","session_end","advisor_calls","work_state_telemetry"];function aE(r){return`received_${r}`}var nd=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,od=/^[A-Za-z0-9_-]{1,128}$/,cE="corrupt",lE="expired",sd=10080*60*1e3,uE=300*1e3;function dE(){return(0,pe.join)(re(),"state","hook-spool")}function Wt(r){if(r===null||typeof r!="object")return JSON.stringify(r)??"null";if(Array.isArray(r))return`[${r.map(Wt).join(",")}]`;let e=r;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Wt(e[n])}`).join(",")}}`}function ad(r){return`remote_${r.kind}-${(0,Bt.createHash)("sha256").update(Wt(r)).digest("hex")}`}function id(r){return/^remote_[a-z_]+-[a-f0-9]{64}$/.test(r)}function fE(r,e){let t=e.toolUseId;return typeof t=="string"&&od.test(t)?`${(0,Bt.createHash)("sha256").update(e.contentSessionId).update("\0").update(V(e.platformSource)).digest("hex")}-${t}`:(0,Bt.createHash)("sha256").update(r).update("\0").update(e.contentSessionId).update("\0").update(Wt(e)).digest("hex")}function Go(r){return typeof r=="string"&&r.length>0}function ys(r){let e;try{e=JSON.parse(r)}catch(i){return{corruptReason:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}}if(e===null||typeof e!="object")return{corruptReason:"not an object"};let t=e;if(!oE.includes(t.kind))return{corruptReason:`unknown kind ${JSON.stringify(t.kind)}`};if(typeof t.enqueuedAtEpochMs!="number"||!Number.isFinite(t.enqueuedAtEpochMs))return{corruptReason:"missing enqueuedAtEpochMs"};let n=t.payload;if(n===null||typeof n!="object"||!Go(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=t.kind;return(s==="observation"||s==="file_edit")&&!Go(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"}:s==="work_state_telemetry"&&(!Go(n.eventId)||!["main","subagent","unknown",void 0].includes(n.agentRole)||(n.kind==="instruction"?!["returned","disabled","excluded","missing","unknown"].includes(String(n.state)):n.kind!=="mcp"||!["read","write"].includes(String(n.tool))||!["ok","error","excluded","disabled","unknown"].includes(String(n.outcome))))?{corruptReason:"invalid work-state telemetry shape"}:{kind:s,payload:{...n,platformSource:V(n.platformSource)},enqueuedAtEpochMs:t.enqueuedAtEpochMs}}var zo=0;function pE(){return zo=Math.max(Date.now(),zo+1),zo}var bs=class{constructor(e=dE()){this.directory=e}directory;get corruptDirectory(){return(0,pe.join)(this.directory,cE)}get expiredDirectory(){return(0,pe.join)(this.directory,lE)}enqueue(e,t,n){let s={...t,platformSource:V(t.platformSource)},i=(0,pe.join)(this.directory,`${e}-${fE(e,s)}.json`),o=s.toolUseId;if(typeof o=="string"&&od.test(o)){let c=(0,pe.join)(this.directory,`${e}-${o}.json`);try{let l=ys((0,L.readFileSync)(c,"utf8"));!("corruptReason"in l)&&l.kind===e&&l.payload.contentSessionId===s.contentSessionId&&l.payload.platformSource===s.platformSource&&(i=c)}catch{}}let a=this.existingEnqueuedAt(i)??n??pE();return K(i,{kind:e,payload:s,enqueuedAtEpochMs:a}),i}entries(){return this.readEntries().files.map(e=>e.entry)}hasEntries(){try{let e=(0,L.opendirSync)(this.directory);try{for(let t=e.readSync();t;t=e.readSync())if(t.isFile()&&nd.test(t.name))return!0}finally{e.closeSync()}}catch(e){["ENOENT","ENOTDIR"].includes(e.code??"")||f.warn("HOOK","Could not inspect pending hook spool files",{},e instanceof Error?e:new Error(String(e)))}return!1}enqueueRemote(e,t){let n=ad(e),s=aE(n);return!t.isConsumed(n)&&!t.isConsumed(s)&&(K((0,pe.join)(this.directory,`${n}.json`),e),t.markConsumed(s,Date.now())),n}async drain(e,t,n={}){let{files:s,quarantined:i,omitted:o}=this.readEntries(n.maxEntries),a=i,c=0,l=o,u=0;t?.pruneConsumedBefore(Date.now()-sd);let d=new Set;for(let[g,p]of s.entries()){if(n.shouldContinue&&!n.shouldContinue()){l+=s.length-g;break}let m=p.filename.replace(/\.json$/,"");if(t?.isConsumed(m)){f.info("HOOK","Hook spool entry was already handed to ingest before a restart; removing it without ingesting again",{kind:p.entry.kind,contentSessionId:p.entry.payload.contentSessionId,file:p.filename}),this.unlinkEntry(p)?(id(m)||t.clearConsumed(m),c++):l++;continue}let h=JSON.stringify([p.entry.payload.contentSessionId,p.entry.payload.platformSource]);if((p.entry.kind==="summarize"||p.entry.kind==="session_end")&&d.has(h)){l++;continue}let _=!1,E=()=>{if(!_){_=!0;try{t?.markConsumed(m,Date.now())}catch(w){f.error("HOOK","Could not record a hook spool hand-off marker; a crash before the file is removed would ingest it twice",{kind:p.entry.kind,contentSessionId:p.entry.payload.contentSessionId,file:p.filename},w instanceof Error?w:new Error(String(w)))}}},y;try{y=await e(p.entry,E)}catch(w){f.warn("HOOK",_?"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:p.entry.kind,contentSessionId:p.entry.payload.contentSessionId,file:p.filename},w instanceof Error?w:new Error(String(w))),y=!1}if(_&&(y=!0),y==="rejected"){this.unlinkTransferredEntry(p,"Remote worker permanently rejected this capture event")?a++:l++;continue}if(y==="expired"){this.expireIfPastWindow(p,uE,"unknown-session grace window")?u++:l++;continue}if(!y){this.expireIfPastWindow(p,sd,"retry window")?u++:((p.entry.kind==="observation"||p.entry.kind==="file_edit")&&d.add(h),l++);continue}this.unlinkEntry(p,n.verifyUnchanged)?(id(m)||t?.clearConsumed(m),c++):l++}return{drained:c,retained:l,quarantined:a,expired:u}}unlinkEntry(e,t=!1){if(t)return this.unlinkTransferredEntry(e);try{return(0,L.unlinkSync)(e.path),!0}catch(n){return n.code==="ENOENT"?!0:(f.warn("HOOK","Hook spool entry was ingested but could not be removed",{kind:e.entry.kind,file:e.filename},n instanceof Error?n:new Error(String(n))),!1)}}unlinkTransferredEntry(e,t){let n=(0,pe.join)(this.directory,`${e.entry.kind}-ack-${(0,Bt.randomBytes)(16).toString("hex")}.json`);try{(0,L.renameSync)(e.path,n)}catch(s){return s.code==="ENOENT"?!0:(f.warn("HOOK","Could not claim an acknowledged spool file; retaining it",{},s instanceof Error?s:new Error(String(s))),!1)}try{let s=ys((0,L.readFileSync)(n,"utf8"));if(!("corruptReason"in s)&&Wt(s)===Wt(e.entry))return t?((0,L.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,L.renameSync)(n,(0,pe.join)(this.corruptDirectory,e.filename)),f.error("HOOK",t,{file:e.filename,corruptDirectory:this.corruptDirectory})):(0,L.unlinkSync)(n),!0;try{(0,L.linkSync)(n,e.path),(0,L.unlinkSync)(n)}catch(i){i.code!=="EEXIST"&&f.warn("HOOK","Could not restore a replaced spool file; its claimed copy remains queued",{},i instanceof Error?i:new Error(String(i)))}}catch(s){f.warn("HOOK","Could not remove an acknowledged spool file; retaining it for retry",{},s instanceof Error?s:new Error(String(s)))}return!1}expireIfPastWindow(e,t,n){let s=Date.now()-e.entry.enqueuedAtEpochMs;if(s<=t)return!1;let i={kind:e.entry.kind,contentSessionId:e.entry.payload.contentSessionId,ageMinutes:Math.round(s/6e4),ageHours:Math.round(s/36e5),file:e.filename,expiredDirectory:this.expiredDirectory};try{(0,L.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,L.renameSync)(e.path,(0,pe.join)(this.expiredDirectory,e.filename))}catch(o){return f.error("HOOK",`Hook spool entry is past its ${n} but could not be moved to expired/; keeping it`,i,o instanceof Error?o:new Error(String(o))),!1}return f.error("HOOK",`Hook spool entry was never accepted within its ${n}; moved to expired/`,i),!0}existingEnqueuedAt(e){if(!(0,L.existsSync)(e))return null;try{let t=ys((0,L.readFileSync)(e,"utf-8"));return"corruptReason"in t?null:t.enqueuedAtEpochMs}catch(t){return f.debug("HOOK","Could not read existing hook spool entry; writing a fresh one",{entryPath:e},t instanceof Error?t:new Error(String(t))),null}}quarantine(e,t){let n=(0,pe.join)(this.directory,e);try{return(0,L.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,L.renameSync)(n,(0,pe.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:t,corruptDirectory:this.corruptDirectory}),!0}catch(s){return f.error("HOOK","Corrupt hook spool entry could not be quarantined; leaving it in place",{file:e,reason:t},s instanceof Error?s:new Error(String(s))),!1}}readEntries(e=Number.POSITIVE_INFINITY){if(!(0,L.existsSync)(this.directory))return{files:[],quarantined:0,omitted:0};let t;try{t=(0,L.readdirSync)(this.directory).filter(o=>nd.test(o))}catch(o){return f.warn("HOOK","Could not list hook spool entries",{directory:this.directory},o instanceof Error?o:new Error(String(o))),{files:[],quarantined:0,omitted:0}}let n=[],s=0,i=0;for(let o of t){let a=(0,pe.join)(this.directory,o),c;try{c=(0,L.readFileSync)(a,"utf-8")}catch(u){u.code!=="ENOENT"&&f.warn("HOOK","Could not read hook spool entry; will retry",{file:o},u instanceof Error?u:new Error(String(u)));continue}let l=ys(c);if("corruptReason"in l){this.quarantine(o,l.corruptReason)&&s++;continue}n.push({entry:l,path:a,filename:o}),n.length>e&&(n.sort((u,d)=>u.entry.enqueuedAtEpochMs-d.entry.enqueuedAtEpochMs||u.filename.localeCompare(d.filename)),n.pop(),i++)}return n.sort((o,a)=>o.entry.enqueuedAtEpochMs-a.entry.enqueuedAtEpochMs||o.filename.localeCompare(a.filename)),{files:n,quarantined:s,omitted:i}}};var fd=require("child_process"),pd=require("fs");W();var I=require("zod");var ld=1;var ws=I.z.object({contentSessionId:I.z.string().min(1).max(512),platformSource:I.z.string().min(1).max(128),cwd:I.z.string().max(32768).optional()}).passthrough(),cd=ws.extend({toolName:I.z.string().min(1).max(512),toolInput:I.z.unknown().optional(),toolResponse:I.z.unknown().optional(),toolUseId:I.z.string().max(2048).optional(),agentId:I.z.string().max(128).optional(),agentType:I.z.string().max(128).optional()}),Ht=I.z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),gE=I.z.discriminatedUnion("kind",[I.z.object({kind:I.z.literal("observation"),payload:cd,enqueuedAtEpochMs:Ht}),I.z.object({kind:I.z.literal("file_edit"),payload:cd,enqueuedAtEpochMs:Ht}),I.z.object({kind:I.z.literal("summarize"),payload:ws.extend({lastAssistantMessage:I.z.string(),observedModel:I.z.string().max(1024).optional(),observedBilling:I.z.string().max(1024).optional()}),enqueuedAtEpochMs:Ht}),I.z.object({kind:I.z.literal("session_end"),payload:ws,enqueuedAtEpochMs:Ht}),I.z.object({kind:I.z.literal("advisor_calls"),payload:ws.extend({transcriptPath:I.z.string().max(32768).optional(),calls:I.z.array(I.z.object({toolUseId:I.z.string().min(1).max(2048),advice:I.z.string(),advisorModel:I.z.string().nullable().optional(),occurredAtEpoch:Ht,lastUserMessage:I.z.string().nullable().optional(),transcriptByteOffset:I.z.number().int().nonnegative().nullable().optional()}).passthrough()).min(1).max(128)}),enqueuedAtEpochMs:Ht})]),hM=I.z.object({protocolVersion:I.z.literal(ld),entry:gE}).strict();function ud(r){if(typeof r!="string")return"";let e=r.trim();return e.length<=1024&&/^[\x20-\x7e]+$/.test(e)?e:""}function dd(r,e="auto"){if(e=e.trim().toLowerCase(),e==="http")return!0;if(e==="filesystem"||!r)return!1;let t=r.toLowerCase().replace(/^\[|\]$/g,"");try{t=new URL(`http://${mr(r)}`).hostname.replace(/^\[|\]$/g,"")}catch{}return!(t==="localhost"||t.endsWith(".localhost")||t==="0.0.0.0"||t==="::"||t==="::1"||/^127\.\d+\.\d+\.\d+$/.test(t)||/^::ffff:127\.\d+\.\d+\.\d+$/.test(t)||/^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(t))}M();var mE=250,Ts=new Set,vr=null,hE=!1,Mr=null,Vo=!1,qo=!1;function gd(){if(Mr)return Mr;if(Vo)return qo=!0,Promise.resolve();let r=new Promise(e=>{setImmediate(()=>{try{_E()}catch{f.warn("HOOK","Remote hook uploader could not start; retaining the outbox")}finally{e()}})});return Mr=r,Ts.add(r),r.finally(()=>{Ts.delete(r),Mr===r&&(Mr=null)}),r}function _E(){if(!ud(Y().CLAUDE_MEM_WORKER_INGEST_TOKEN)){f.warn("HOOK","Remote hook capture is queued locally; configure CLAUDE_MEM_WORKER_INGEST_TOKEN on the client and worker");return}let e=process.argv[1],t=e&&/worker-service\.(?:cjs|ts)$/.test(e)&&(0,pd.existsSync)(e)?e:xo();if(!t){f.warn("HOOK","Remote hook upload entrypoint is unavailable; retaining the outbox");return}Vo=!0;let n=!1,s=()=>{n||(n=!0,Vo=!1,qo&&(qo=!1,gd()))};try{let i=(0,fd.spawn)(process.execPath,[t,"upload-spool"],{cwd:re(),env:Le(process.env),detached:!0,windowsHide:!0,stdio:"ignore"});i.once("error",()=>{f.warn("HOOK","Remote hook uploader could not start; retaining the outbox"),s()}),i.once("exit",o=>{o!==0&&f.warn("HOOK","Remote hook uploader exited unsuccessfully; retaining the outbox",{code:o}),s()}),i.unref()}catch{f.warn("HOOK","Remote hook uploader could not start; retaining the outbox"),s()}}function EE(){let r=Y();if(dd(br(),r.CLAUDE_MEM_HOOK_SPOOL_TRANSPORT))return hE=!0,gd();if(vr)return vr;let e=(async()=>{try{await(await Fe("/api/spool/nudge",{method:"POST",timeoutMs:mE})).body?.cancel()}catch(t){f.debug("HOOK","Hook spool nudge not delivered (worker will pick the entry up on its own)",{error:t instanceof Error?t.message:String(t)})}})();return vr=e,Ts.add(e),e.finally(()=>{Ts.delete(e),vr===e&&(vr=null)}),e}function Or(r,e){let t=new bs().enqueue(r,e);return f.debug("HOOK","Hook event spooled for the worker",{kind:r,entryPath:t}),EE(),t}M();function As(r,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(r.toLowerCase()):!1}var Yo="write_file",md={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:s}=r,i=V(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!cs(t))return f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};let o={filePath:n,edits:s},a={success:!0},c=_s();if(c.runtime==="server"){if(As(Yo,Y().CLAUDE_MEM_SKIP_TOOLS))return f.debug("HOOK","Server runtime: file edit excluded by CLAUDE_MEM_SKIP_TOOLS",{filePath:n}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};let l={projectId:c.projectId,contentSessionId:e,platformSource:i,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:Yo,tool_input:o,tool_response:a,cwd:t,platformSource:i}};try{return await c.client.recordEvent(l),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),{continue:!0,suppressOutput:!0}}catch(u){if(hs(u)&&u.isFallbackEligible())Es(u.kind,{status:u.status,message:u.message,route:"/v1/events"});else return f.error("HOOK","Server file edit failed (non-recoverable)",{error:u instanceof Error?u.message:String(u)}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS}}}return Or("file_edit",{contentSessionId:e,platformSource:i,toolName:Yo,toolInput:o,toolResponse:a,cwd:t}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};W();M();var Me=require("fs"),Ir=require("path");M();le();M();W();var Cr="<claude-mem-context>",Rs="</claude-mem-context>";function hd(r){let e=r.indexOf(Cr);if(e===-1)return null;let t=r.indexOf(Rs,e+Cr.length);return t===-1?null:{start:r.lastIndexOf(Cr,t),end:t+Rs.length}}var nO=j.settings();function _d(r,e){let t=`${Cr}
20
+ `).trim()}function ro(r){let e=ml(r);return e.length===0?"":(e=eo(e),e=Lm(e),e=to(e),e=Nm(e),e=Fm(e),e=Um(e),e)}function hl(r){try{let e=$m(ro(ml(r)));return e.length>fl?e.slice(0,fl):e}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,t),""}}function _l(r){return(typeof r=="string"?r:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var Bm=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","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","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","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(r=>["read","write"].flatMap(e=>[`${r}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(t=>`${r}_${e}_${t}_count`)]))]),El=200;function Wm(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Bm.has(t))continue;let n=r[t];if(typeof n=="string"){let s=n.length>El?n.slice(0,El):n;e[t]=ro(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Un(r){let e={};try{Wm(r,e)}catch{}return e}var no=me(require("os"),1);M();var Hm="14.0.0",jm="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Km="https://us.i.posthog.com";function $n(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||jm}function Bn(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Km}var Gm=["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"];function Wn(r){let e={};for(let t of Gm)r[t]!==void 0&&(e[t]=r[t]);return e}function zm(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||no.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Hn(){return{version:Hm,os:process.platform,os_version:no.default.release(),is_wsl:zm(),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 Vm=2e3;async function Sl(r,e,t){try{if(!Nn(process.env,hr()))return;let n=Un({...Hn(),...e??{}});if(t?.person?n.$set=Wn(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
21
+ `);return}let s=$n(),i=new AbortController,o=setTimeout(()=>i.abort(),Vm);try{await qm(s,r,n,i.signal)}finally{clearTimeout(o)}}catch{}}async function qm(r,e,t,n){await fetch(`${Bn()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Fn(),properties:t}),signal:n})}var ue=me(require("path"),1),go=require("os"),fe=require("fs"),qn=require("child_process");M();M();M();var oe=me(require("path"),1),Ut=require("fs"),Vn=require("os"),lo=require("child_process");lr();W();M();var jn=require("fs"),Ze=me(require("path"),1);M();var _r={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function yl(r){let e=Ze.default.join(r,".git"),t;try{t=(0,jn.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)}),_r}if(!t.isFile())return _r;let n;try{n=(0,jn.readFileSync)(e,"utf-8").trim()}catch(c){return f.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),_r}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return _r;let i=Ze.default.resolve(Ze.default.dirname(e),s[1]),o=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(o){let c=o[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Ze.default.basename(r),parentRepoPath:c,parentProjectName:Ze.default.basename(c)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Ze.default.basename(r),parentRepoPath:c,parentProjectName:Ze.default.basename(c)}}return _r}var Tl=require("fs");var so=require("path");lr();M();function bl(r){let e=Pe(r.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function wl(r,e,t){let n=bl(r);return n.test(e)||n.test(t)?!0:r.replace(/\\/g,"/").endsWith("/**")?bl(r.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function io(r,e){if(!e.length)return!1;let t=r.replace(/\\/g,"/"),n=(0,so.basename)(t);for(let s of e){let i=s.trim();if(i)try{if(wl(i,t,n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}}return!1}function Kn(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,so.basename)(t),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{if(wl(i,t,n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}M();function Al(r){let e=r;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return f.warn("PROJECT_NAME","CLAUDE_MEM_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","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let t=[];for(let n of e){let s=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(o=>typeof o=="string"&&o.trim()!==""):[];if(!s||i.length===0){f.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:s});continue}t.push({name:s,patterns:i})}return t}function Ym(r){try{return(0,Tl.realpathSync)(r)}catch{return r}}function oo(r,e){if(e.length===0)return null;let t=[...new Set([r,Ym(r)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(t.some(s=>io(s,n.patterns)))return n.name;return null}var uo="unknown-project";function Ml(r){try{return(0,lo.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:r},t),null}}var Jm=[".claude-mem-project",".claude-mem.json"],Xm=64;function Ol(r){try{return(0,Ut.realpathSync)(r)}catch{return r}}function Qm(r,e){let t=oe.default.relative(e,r);return t===""||!t.startsWith("..")&&!oe.default.isAbsolute(t)}function Zm(){return[(0,Vn.homedir)(),(0,Vn.tmpdir)(),ut].flatMap(r=>{let e=oe.default.resolve(r);return[e,Ol(e)]})}function Cl(r){let e=Zm(),t=oe.default.resolve(r);if([oe.default.resolve(ut),Ol(oe.default.resolve(ut))].some(s=>Qm(t,s)))return null;for(let s=0;s<Xm;s++){if(e.includes(t))return null;let i=oe.default.dirname(t);if(i===t)return null;if(Jm.some(o=>(0,Ut.existsSync)(oe.default.join(t,o))))return t;t=i}return null}function co(r,e){let t=oe.default.basename(e);if(t===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:o}),o}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),uo}return t}var eh="CLAUDE_MEM_PROJECT_NAME_SOURCE",Gn=null;function Rl(){try{return(0,Ut.statSync)(ne).mtimeMs}catch{return-1}}function Il(){let r=Rl();if(r===-1)return H.getAllDefaults();if(Gn&&Gn.mtimeMs===r)return Gn.settings;let e=H.loadFromFile(ne);return Gn={mtimeMs:Rl(),settings:e},e}function th(){let r=process.env[eh]??Il().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(r??"path").trim().toLowerCase()==="git-remote"}var rh="CLAUDE_MEM_PROJECT_ENVIRONMENTS",zn=null;function Pl(){let r=process.env[rh]??Il().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!zn||zn.raw!==r)&&(zn={raw:r,environments:Al(r)}),zn.environments}function nh(r){let e=(r??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),s=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=s?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),o=s?.[1]??i?.[1];if(!o)return null;let a=o.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function sh(r){try{let e=(0,lo.execFileSync)("git",["remote","get-url","origin"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return nh(e)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:r},t),null}}var ao=new Map;function kl(r){return th()?(ao.has(r)||ao.set(r,sh(r)),ao.get(r)??null):null}function ih(r,e=process.platform){if(!r||r.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),uo;let t=Pe(r,e),n=oo(t,Pl());if(n)return n;let s=Ml(t),i=s?kl(s):null;if(i)return i;let o=s??Cl(t)??t;return co(r,o)}function xl(r,e){return e===r?r:`${r}/${e}`}function oh(r,e){if(!r.isSubmodule||!r.parentRepoPath)return null;let t=oe.default.relative(r.parentRepoPath,e);return!t||t.startsWith("..")||oe.default.isAbsolute(t)?null:t.split(oe.default.sep).join("/")}function mt(r,e=process.platform){if(!r||r.trim()===""){let c=ih(r,e);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let t=Pe(r,e),n=Ml(t),s=ah(r,t,n),i=n?kl(n):null,o=i?vl(s,i,"git-remote"):s,a=oo(t,Pl());return a?vl(o,a,"environment"):o}function vl(r,e,t){return{primary:e,parent:null,isWorktree:r.isWorktree,isSubmodule:r.isSubmodule,allProjects:[...r.allProjects.filter(n=>n!==e),e],keySource:t}}function ah(r,e,t){let n=t?null:Cl(e),s=co(r,t??n??e),i=t??e,o=yl(i);if((o.isWorktree||o.isSubmodule)&&o.parentProjectName){let a=o.parentProjectName,c,l;return o.isSubmodule?(c=`${a}/${oh(o,i)??s}`,l=s!==a?[s]:[]):(c=xl(a,s),l=c===a?[`${a}/${s}`]:[]),{primary:c,parent:a,isWorktree:o.isWorktree,isSubmodule:o.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(u=>u!==c).concat(c),keySource:"path"}}if(n&&oe.default.resolve(n)!==oe.default.resolve(e)){let a=co(r,e);if(a!==s&&a!==uo)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"}}W();var Dl=xe(Q.POWERSHELL_COMMAND);function lh(r){return r===void 0?Dl:Math.max(1,Math.min(Dl,r))}var wR=j.dataDir(),TR=j.workerPid(),uh="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite.";function dh(r){try{return(0,fe.realpathSync)(r)}catch{return null}}function fo(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function fh(r,e){let t=e==="win32"?"where.exe":"which",n=[r],s;try{s=(0,qn.execFileSync)(t,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t,args:n},o):f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t,args:n},new Error(String(o))),null}return s.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}var po;function mo(r={}){let e=Object.keys(r).length===0;if(e&&po!==void 0)return po;let t=ph(r);return e&&t!==null&&(po=t),t}function Ll(r,e){let t=r?.trim();return t?e==="win32"?[ue.default.join(t,"bin","bun.exe"),ue.default.join(t,"bin","bun"),ue.default.join(t,"bun.exe")]:[ue.default.join(t,"bin","bun"),ue.default.join(t,"bun")]:[]}function ph(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(fo(t))return t;let n=r.env??process.env,s=r.homeDirectory??(0,go.homedir)(),i=r.pathExists??fe.existsSync,o=r.lookupInPath??fh,a=r.realpath??dh,c=e==="win32"?[n.BUN,n.BUN_PATH,...Ll(n.BUN_INSTALL,e),ue.default.join(s,".bun","bin","bun.exe"),ue.default.join(s,".bun","bin","bun"),n.USERPROFILE?ue.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?ue.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?ue.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?ue.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...Ll(n.BUN_INSTALL,e),ue.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?ue.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let g=d?.trim();if(g&&(fo(g)&&i(g)||g.toLowerCase()==="bun"))return g}let l=o("bun",e)?.trim();if(!l||!fo(l))return null;let u=a(l)??l;return i(u)?u:null}function ho(){let r=j.dataDir();return(0,fe.mkdirSync)(r,{recursive:!0}),r}function gh(r,e,t=ho()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(r)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(t)}' -WindowStyle Hidden`}function mh(r=process.env){let e=r.SystemRoot||r.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function hh(r,e,t=ho()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(gh(r,e,t),"utf16le").toString("base64")]}function _o(r,e,t,n=process.platform,s){if(n==="win32"){let u=mh(t),d=hh(r,e),g=lh(s);try{let p=(0,qn.spawnSync)(u,d,{stdio:"ignore",windowsHide:!0,env:t,timeout:g,killSignal:"SIGTERM"});if(p.error)throw p.error;if(p.signal)throw new Error(`powershell Start-Process killed by signal=${p.signal} after ${g}ms`);if(p.status!==0)throw new Error(`powershell Start-Process exited ${p.status??"null"}`);return 0}catch(p){let m=p instanceof Error?p:new Error(String(p));f.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:r,powershell:u},m);return}}let i="/usr/bin/setsid",o=(0,fe.existsSync)(i),a=o?i:r,l=Gi(a,o?[r,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:ho(),env:t});if(l.on("error",u=>{f.error("SYSTEM",uh,{runtimePath:r,execPath:a},u)}),l.pid!==void 0)return l.unref(),l.pid}var Fl=me(require("net"),1);M();W();function Nl(r){let e=r?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Eo="Set CLAUDE_MEM_WORKER_PORT to a port between 1024 and 65535 and CLAUDE_MEM_WORKER_HOST to an address of this machine (127.0.0.1 by default) in claude-mem settings";function So(){return H.loadFromFile(ne).CLAUDE_MEM_WORKER_HOST}function Ul(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}var ht=5e3;async function $l(r,e,t="GET",n=ht){let s=await fetch(`http://${Ul(So())}:${r}${e}`,{method:t,signal:AbortSignal.timeout(Math.max(1,n))}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}async function Bl(r,e=ht){let t=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${Ul(So())}:${r}/api/health`,{signal:AbortSignal.timeout(Math.max(1,t-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:r,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,error:String(s)})}let n=await Yn(r,Math.max(1,t-Date.now()));return n==="occupied"||n==="indeterminate"}async function Yn(r,e=ht){return(await _h(r,e)).occupancy}function _h(r,e=ht){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(t=>{let n=!1,s=!1,i=!1,o;try{o=Fl.default.createServer()}catch{t({occupancy:"indeterminate"});return}let a=u=>{if(i){u?.();return}i=!0;try{o.close(u)}catch(d){u?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(s)a();else try{o.close()}catch{}l({occupancy:"indeterminate"})},e),l=u=>{n||(n=!0,clearTimeout(c),t(u))};o.once("error",u=>{if(s)a();else try{o.close()}catch{}u.code==="EADDRINUSE"?l({occupancy:"occupied"}):Nl(u)?l({occupancy:"unbindable",bindErrorCode:u.code}):l({occupancy:"indeterminate"})}),o.once("listening",()=>{if(s=!0,n){a();return}try{a(u=>l({occupancy:u?"indeterminate":"free"}))}catch{l({occupancy:"indeterminate"})}});try{o.listen(r,So())}catch{try{o.close()}catch{}l({occupancy:"indeterminate"})}})}async function Eh(r,e,t,n){let s=Date.now()+t;for(;Date.now()<s;){try{let o=s-Date.now();if((await $l(r,e,"GET",Math.min(ht,o))).ok)return!0}catch(o){o instanceof Error?f.debug("SYSTEM",n,{},o):f.debug("SYSTEM",n,{error:String(o)})}let i=Math.min(500,s-Date.now());i>0&&await new Promise(o=>setTimeout(o,i))}return!1}function Wl(r,e=3e4){return Eh(r,"/api/health",e,"Service not ready yet, will retry")}async function Sh(r,e=ht){try{let t=await $l(r,"/api/health","GET",e);return t.ok?JSON.parse(t.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Hl(r,e,t=ht){let n=e??"unknown",s=await Sh(r,t);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}M();var Jn=require("path"),Z=require("fs");W();M();var Kl=9e4,HR=Kl/3;function Gl(){return(0,Jn.join)(re(),"spawn.lock")}function jl(r){try{let e=JSON.parse((0,Z.readFileSync)(r,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function yh(r){if(r===null)return null;try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}function yo(){let r=Gl(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,Z.mkdirSync)((0,Jn.dirname)(r),{recursive:!0}),(0,Z.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},s),!0;if(t>0)return!1;let o;try{o=(0,Z.statSync)(r).mtimeMs}catch{continue}let a=jl(r),c=null;if(a===null)try{c=(0,Z.readFileSync)(r,"utf-8")}catch{continue}if(Date.now()-o<=Kl&&yh(a)!==!1)return!1;let u;try{u=(0,Z.statSync)(r).mtimeMs}catch{continue}if(u!==o)return!1;if(a!==null){if(jl(r)!==a)return!1}else try{if((0,Z.readFileSync)(r,"utf-8")!==c)return!1}catch{continue}try{(0,Z.unlinkSync)(r)}catch{return!1}}return!1}function bo(){let r=Gl();try{if(JSON.parse((0,Z.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,Z.unlinkSync)(r)}catch{}}var Yl=require("node:child_process"),Er=require("node:fs"),Jl=require("node:util");M();W();var Xn=(0,Jl.promisify)(Yl.execFile),bh=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function zl(r){return bh.test(r.trim())}function wh(r,e){if(!r)return!1;let t=r.toLowerCase().replace(/\\/g,"/"),n=t.indexOf("--data-dir");if(n<0)return!1;let s=t.slice(n+10).trim();if(s.startsWith('"')){let o=s.indexOf('"',1);s=o<0?s.slice(1):s.slice(1,o)}let i=e.toLowerCase().replace(/\\/g,"/");return s===i||s.startsWith(i)&&s[i.length]==="/"}function Qn(r,e){return e===void 0?r:Math.max(1,Math.min(r,e))}async function Th(r){try{let e=await Xn("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:Qn(3e4,r),windowsHide:!0,maxBuffer:33554432}),t=JSON.parse(e.stdout),n=Array.isArray(t)?t:t===null?[]:[t],s=[];for(let i of n){let o=typeof i.Name=="string"?i.Name.trim():"";if(!o)continue;let a=typeof i.ProcessId=="number"?i.ProcessId:Number.parseInt(String(i.ProcessId),10),c=typeof i.ParentProcessId=="number"?i.ParentProcessId:Number.parseInt(String(i.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||s.push({pid:a,ppid:c,name:o,cmdline:typeof i.CommandLine=="string"?i.CommandLine:null,startToken:typeof i.StartToken=="string"&&i.StartToken.length>0?i.StartToken:null})}return s}catch(e){return f.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function Ah(r,e){try{let t=await Xn("netstat",["-ano"],{timeout:Qn(15e3,e),windowsHide:!0,maxBuffer:16777216});return Oh(t.stdout,r)}catch(t){return f.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:r,error:t instanceof Error?t.message:String(t)}),null}}async function Rh(r,e){try{let t=await Xn("lsof",["-nP",`-iTCP:${r}`,"-sTCP:LISTEN","-t"],{timeout:Qn(1e4,e),maxBuffer:1048576});return vh(t.stdout)}catch(t){let n=t;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(f.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:r,error:t instanceof Error?t.message:String(t)}),null)}}function vh(r){let e=new Set;for(let t of r.split(/\r?\n/)){let n=Number.parseInt(t.trim(),10);Number.isInteger(n)&&n>0&&e.add(n)}return[...e]}async function Mh(r,e){try{let n=(await Xn("ps",["-p",String(r),"-o","command="],{timeout:Qn(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function Oh(r,e){let t=new Set,n=`:${e}`;for(let s of r.split(/\r?\n/)){let i=s.trim();if(!/^TCP\b/i.test(i))continue;let o=i.split(/\s+/);if(!o[1]?.endsWith(n)||o[3]!=="LISTENING")continue;let c=Number.parseInt(o[4]??"",10);Number.isInteger(c)&&c>0&&t.add(c)}return[...t]}var Ch=/worker-service/i,Xl=1500,Ql=1e3,wo=5500,Vl=2*Xl+Ql+wo;async function Ih(r,e){let t=e.readOwnedWorker();if(t===null||t.port!==r)return null;let n=(u,d={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:r,pid:t.pid,reason:u,...d}),{reclaimed:!1,reason:u,killedPids:[]}),s=(e.now()-Date.parse(t.startedAt))/1e3;if(!Number.isFinite(s)||s<e.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:s,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(Ql),await e.probeHealth(r))return n("owner-responding");let i=await e.listOwners(r);if(i===null)return n("netstat-unreadable");if(!i.includes(t.pid))return f.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:r,pid:t.pid,listeners:i}),null;let o=e.readHeartbeat();if(o!==null&&o.pid===t.pid){let u=e.now(),d=Math.max(0,u-o.beatAtMs),g=Math.max(0,u-o.lastResponseAtMs);if(d<e.heartbeatStaleMs){if(g<e.maxSilentProtectionMs)return n("owner-progressing",{heartbeatAgeMs:Math.round(d),sinceLastResponseMs:Math.round(g)});f.warn("PROCESS","Worker finished no response within the protection window despite a fresh liveness heartbeat",{port:r,pid:t.pid,sinceLastResponseMs:Math.round(g),maxSilentProtectionMs:e.maxSilentProtectionMs})}}let a=await e.readIdentity(t.pid),c=t.startToken!==void 0&&a.startToken!==null&&a.startToken!==t.startToken;if(c||a.cmdline===null||!Ch.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:r,pid:t.pid,ageSeconds:Math.round(s)});try{await e.killTree(t.pid,{expectedStartToken:a.startToken??t.startToken??void 0,signalMode:"graceful"})}catch(u){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:r,pid:t.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let l=await e.listOwners(r);return l!==null&&l.length===0?(f.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:r,killedPids:[t.pid]}),{reclaimed:!0,killedPids:[t.pid]}):(f.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:r,pid:t.pid,stillOwnedBy:l}),{reclaimed:!1,reason:"still-bound",killedPids:[t.pid]})}async function Ph(r,e,t,n){let s=Ne(r),i=e?(await t(n))?.find(o=>o.pid===r)?.cmdline??null:await Mh(r,n);return Re(r,s)?{startToken:s,cmdline:i}:{startToken:null,cmdline:null}}async function Zl(r,e={}){let t=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,i=b=>s!==null&&s-n()<b,o=()=>s===null?void 0:Math.max(1,s-n());if(i(Vl))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:r,remainingMs:o(),neededMs:Vl}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((b,C)=>t()?Ah(b,C):Rh(b,C)),c=b=>a(b,o()),l=e.readTable??Th,u=()=>l(o()),d=e.killTree??((b,C)=>he(b,C)),g=e.dataDir??(()=>U),p=e.readIdentity??((b,C)=>Ph(b,t(),l,C)),m=await Ih(r,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??Qe,probeHealth:e.probeHealth??(b=>Wl(b,Xl)),readIdentity:b=>p(b,o()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??wc(),readHeartbeat:e.readHeartbeat??(()=>Lh()),heartbeatStaleMs:e.heartbeatStaleMs??xh(),maxSilentProtectionMs:e.maxSilentProtectionMs??Dh,now:n,sleep:e.sleep??(b=>new Promise(C=>setTimeout(C,b))),hasKillBudget:()=>!i(wo)});if(m!==null)return m;if(!t())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await c(r);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let _=await u();if(_===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(b=>J(b)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let y=new Map;for(let b of _){let C=y.get(b.ppid);C?C.push(b):y.set(b.ppid,[b])}let w=new Map,R=new Set,P=b=>{for(let C of y.get(b)??[])R.has(C.pid)||(R.add(C.pid),P(C.pid),zl(C.name)&&w.set(C.pid,C))};for(let b of h)P(b);let O=g();if(O)for(let b of _)w.has(b.pid)||zl(b.name)&&wh(b.cmdline,O)&&w.set(b.pid,b);if(w.size===0)return f.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:r,deadOwners:h,processTableRows:_.length,dataDir:O??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};f.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:r,deadOwners:h,targets:[...w.values()].map(b=>({pid:b.pid,name:b.name}))});let S=[];for(let b of w.values()){if(i(wo))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:r,killedPids:S}),{reclaimed:!1,reason:"out-of-budget",killedPids:S};try{await d(b.pid,{expectedStartToken:b.startToken,signalMode:"immediate"}),S.push(b.pid)}catch(C){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:r,pid:b.pid},C instanceof Error?C:new Error(String(C))),{reclaimed:!1,reason:"kill-failed",killedPids:S}}}let T=await c(r);return T!==null&&T.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:r,killedPids:S}),{reclaimed:!0,killedPids:S}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:r,killedPids:S,stillOwnedBy:T}),{reclaimed:!1,reason:"still-bound",killedPids:S})}var kh=12e4,ql={min:1e4,max:36e5};function xh(r=process.env,e=ne){let t=r.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??H.loadFromFile(e,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,n=Number(t);return Number.isSafeInteger(n)&&n>=ql.min&&n<=ql.max?n:kh}var Dh=6e5;function Lh(r=j.workerHeartbeat()){try{let e=JSON.parse((0,Er.readFileSync)(r,"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}le();var $t=require("fs"),tu=require("module"),et=me(require("path"),1),Nh=["zod/v3","zod/v4","zod/v4-mini"];function eu(r){try{return(0,$t.realpathSync)(r)}catch{return r}}function Fh(r,e){let t=et.default.relative(e,r);return t!==""&&!t.startsWith("..")&&!et.default.isAbsolute(t)}function ru(r){let e;try{let s=JSON.parse((0,$t.readFileSync)(et.default.join(r,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let t=et.default.join(r,"node_modules"),n=e.filter(s=>!(0,$t.existsSync)(et.default.join(t,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,tu.createRequire)(et.default.join(t,"noop.js")),i=eu(et.default.join(t,"zod"));for(let o of Nh)try{let a=s.resolve(o,{paths:[t]});Fh(eu(a),i)||n.push(o)}catch{n.push(o)}}return n}function mu(r,e,t){let n=process.env[r];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=t.min&&s<=t.max)return s;f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var St=mu("CLAUDE_MEM_HEALTH_TIMEOUT_MS",xe(Q.HEALTH_CHECK),{min:500,max:3e5}),Sr=mu("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",xe(Q.HOOK_READINESS_WAIT),{min:0,max:3e5}),Uh=5e3,$h={min:500,max:3e5},Bh={min:500,max:Q.SESSION_INIT_REQUEST_MAX},Mo=100;function hu(r=process.env){let e=r.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="on"||t==="yes"}function Wh(r){return hu()?{...r,verbose:!0}:r}function Hh(r){let e={},t=r;for(let n=0;t&&n<4;n++){let s=n===0?"error":`cause${n}`;if(t instanceof Error){let i=t;e[s]={name:t.name,message:t.message,...i.code!==void 0?{code:i.code}:{}},t=t.cause;continue}e[s]=String(t);break}return e}function jh(r,e,t){let n=typeof e.method=="string"?e.method:"GET",s=Hh(t),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:r,method:n},i),je(`[claude-mem] fetch verbose: ${n} ${r} ${i}
22
+ `)}async function Oo(r,e={}){let t=Wh(e);try{return await fetch(r,t)}catch(n){throw hu()&&jh(r,e,n),n}}async function Co(r,e={},t){try{return await Oo(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}function Kh(r,e){let t=new AbortController,n=null,s=null,i=null,o=!1,a=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{o=!0,a(),i!==null&&(clearTimeout(i),i=null)},l=d=>{o||(n=d,c(),t.abort(d))},u=()=>{o||(a(),s=setTimeout(()=>l(new Error(`Request timed out after ${r.idleTimeoutMs}ms idle`)),r.idleTimeoutMs))};if(r.absoluteCapMs!==void 0&&r.absoluteCapMs>0){let d=r.absoluteCapMs;i=setTimeout(()=>l(new Error(`Request timed out after ${d}ms`)),d)}return u(),{signal:e?AbortSignal.any([e,t.signal]):t.signal,touch:u,pause:a,dispose:c,translate:d=>n??d}}async function _u(r,e,t){let n=Kh(t,e.signal),s;try{s=await Oo(r,{...e,signal:n.signal})}catch(l){throw n.dispose(),n.translate(l)}n.touch();let i=s.body,o=i?i.getReader():null,a=!1;async function*c(){if(!o){a=!0,n.dispose();return}try{for(;;){n.touch();let l;try{l=await o.read()}catch(u){throw a=!0,n.translate(u)}if(l.done){a=!0;return}n.pause(),t.onChunk?.(l.value),yield l.value}}finally{n.dispose(),a||await o.cancel()}}return{status:s.status,statusText:s.statusText,ok:s.ok,headers:s.headers,chunks:c(),cancel:async()=>{n.dispose(),o&&!a&&(a=!0,await o.cancel())}}}async function Gh(r,e,t){let n=await _u(r,e,t),s=new TextDecoder,i="";for await(let o of n.chunks)i+=s.decode(o,{stream:!0});return i+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:i}}var To=null,Ao=null,Zn=null,es=null,ts=null;function nu(){return F.default.join(H.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Io(r={}){return r.readOnly?H.loadFromFile(nu(),!0,r):(Zn!==null||(Zn=H.loadFromFile(nu())),Zn)}function su(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function Eu(r,e,t){let n=process.env[r];if(n!==void 0){let o=su(n,t);return o!==null?o:(f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let s=Io()[r],i=su(s,t);return i!==null?i:(f.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:s,min:t.min,max:t.max}),e)}function Ee(r={}){if(!r.readOnly&&To!==null)return To;let e=parseInt(Io(r).CLAUDE_MEM_WORKER_PORT,10);return r.readOnly||(To=e),e}function br(r={}){if(!r.readOnly&&Ao!==null)return Ao;let e=Io(r).CLAUDE_MEM_WORKER_HOST;return r.readOnly||(Ao=e),e}function zh(){return es!==null||(es=Eu("CLAUDE_MEM_API_TIMEOUT_MS",xe(Q.API_REQUEST),$h)),es}function Su(){return ts!==null||(ts=Math.min(Eu("CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS",ur(),Bh),Tc())),ts}function Po(r){return r===null?null:Math.max(0,r-Date.now())}function ns(r){let e=Po(r);return e!==null&&e<Mo}function tt(r,e){let t=Po(e);return t===null?r:Math.max(1,Math.min(r,t))}function yu(r){return`http://${mr(br())}:${Ee()}${r}`}function Fe(r,e={}){let t=e.method??"GET",n=yu(r),s={method:t};if(e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return Gh(n,s,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(o=>new Response(o.text.length>0?o.text:null,{status:o.status,statusText:o.statusText,headers:o.headers}));let i=e.timeoutMs??zh();return i>0?Co(n,s,i):Oo(n,s)}async function Vh(r){return(await Fe("/api/health",{timeoutMs:r})).ok}async function iu(r=St){return(await Fe("/api/readiness",{timeoutMs:r})).ok}function bu(r){let e=(0,k.existsSync)(F.default.join(r,"plugin","scripts"))?F.default.join(r,"plugin"):r;return F.default.join(e,"scripts","worker-service.cjs")}function qh(r,e){let t=d=>{let g=d.split("-")[0].split(".");return[parseInt(g[0],10)||0,parseInt(g[1],10)||0,parseInt(g[2],10)||0]},[n,s,i]=t(r),[o,a,c]=t(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let l=r.includes("-")?1:0,u=e.includes("-")?1:0;return l!==u?l-u:r<e?1:r>e?-1:0}function Yh(r=F.default.join(F.default.dirname(F.default.dirname(Dt)),"cache","thedotmack","claude-mem")){try{return(0,k.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>F.default.join(r,e)).filter(e=>{try{if(!(0,k.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,k.existsSync)(F.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:bu(e),version:F.default.basename(e)}))}catch{return[]}}function ou(r){try{let e=JSON.parse((0,k.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function Jh(){return{cacheRoot:F.default.join(F.default.dirname(F.default.dirname(Dt)),"cache","thedotmack","claude-mem"),marketplaceRoot:Dt,cwd:process.cwd()}}function ko(r=Jh()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if((0,k.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let t=[...Yh(r.cacheRoot),{scriptPath:bu(F.default.join(r.marketplaceRoot,"plugin")),version:ou(F.default.join(r.marketplaceRoot,"package.json"))},{scriptPath:F.default.join(r.cwd,"plugin","scripts","worker-service.cjs"),version:ou(F.default.join(r.cwd,"package.json"))}];return Zh(t)}function Xh(r){return F.default.dirname(F.default.dirname(r))}function Qh(r){return ru(Xh(r.scriptPath)).length===0}function Zh(r,e=Qh){let t=r.filter(n=>(0,k.existsSync)(n.scriptPath));return t.length===0?null:(t.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:qh(n.version,s.version)),t.find(e)??t[0])}function xo(){return ko()?.scriptPath??null}async function e_(r){let e=r.deadlineAt??null,t=r.backoffMs;for(let n=1;n<=r.attempts;n++){if(ns(e))return!1;if(await Iu(e??Number.POSITIVE_INFINITY))return!0;n<r.attempts&&(await new Promise(s=>setTimeout(s,tt(t,e))),t*=2)}return!1}function au(r){return r instanceof Error&&/^Request timed out after \d+ms idle$/.test(r.message)}function cu(r){return r instanceof Error&&/^Request timed out after \d+ms$/.test(r.message)}async function t_(r){let e;try{e=await _u(yu("/api/ready"),{method:"GET"},{idleTimeoutMs:Uh,absoluteCapMs:Math.max(1,r)})}catch(i){return au(i)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:cu(i)?{outcome:"still_booting",detail:"budget spent before response headers"}:(f.debug("SYSTEM","Worker /api/ready connection failed",{error:i instanceof Error?i.message:String(i)}),{outcome:"not_running"})}let t=()=>e.cancel().catch(i=>{f.debug("SYSTEM","Releasing the /api/ready body failed",{error:i instanceof Error?i.message:String(i)})}),n=e.headers?.get("content-type")??"";if(!e.ok||!n.includes("text/event-stream"))return ss(),await t(),{outcome:"unsupported"};let s=null;try{for await(let i of jc(e.chunks)){if(i.event!=="phase")continue;let o=JSON.parse(i.data);if(s=typeof o.phase=="string"?o.phase:null,s==="ready")return ss(),await t(),{outcome:"ready"};if(s==="failed")return await t(),{outcome:"failed",detail:typeof o.message=="string"?o.message:"unknown init failure"}}}catch(i){return cu(i)?(ss(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):au(i)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${s??"none"})`}:{outcome:"wedged",detail:`stream error: ${i instanceof Error?i.message:String(i)} (last phase ${s??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${s??"none"})`}}async function r_(r){if(r<=0)try{return await iu()?{outcome:"ready"}:{outcome:"still_booting"}}catch(t){return f.debug("SYSTEM","Worker readiness check threw",{},t instanceof Error?t:new Error(String(t))),{outcome:"still_booting"}}let e=Date.now();do{let t=r-(Date.now()-e);try{if(await iu(Math.max(1,Math.min(St,t))))return{outcome:"ready"}}catch(s){f.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let n=r-(Date.now()-e);if(n<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,n)))}while(Date.now()-e<r);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function Bt(r=Sr){let e=r>0?r:St,t=await t_(e);return t.outcome==="ready"&&l_(),t.outcome!=="unsupported"?t:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),r_(r))}async function n_(r=St){try{let t=await(await Fe("/api/health",{timeoutMs:r})).json();return typeof t.version=="string"?t.version:null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("SYSTEM","Worker health-version fetch failed",{},t),null}}async function s_(r=5e3){let e=Date.now()+r;for(;;){let t=e-Date.now();if(t<=0)return!1;if(await Yn(Ee(),Math.min(1e3,t))==="free")return!0;let n=Math.min(200,e-Date.now());n>0&&await new Promise(s=>setTimeout(s,n))}}function wu(r,e){if(!r)return null;try{let t=(0,k.statSync)(r.scriptPath);return JSON.stringify([r.scriptPath,e,t.size,t.mtimeMs,t.ctimeMs])}catch{return null}}function Tu(){return F.default.join(re(),"worker-version-recycle.json")}function i_(r,e){if(r===null||e===null)return!1;try{let t=JSON.parse((0,k.readFileSync)(Tu(),"utf-8"));return t?.buildKey===r&&t?.workerVersion===e}catch{return!1}}async function lu(r,e=null,t=St){let n=await n_(t);if(n!==null&&n!==r){if(e!==null)try{K(Tu(),{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:r,workerVersion:n})}}var Au=3e4;function Do(){return F.default.join(re(),"worker-unresponsive.json")}function o_(){try{let r=JSON.parse((0,k.readFileSync)(Do(),"utf-8"));return typeof r?.pid!="number"||typeof r?.firstUnresponsiveAtEpochMs!="number"?null:{pid:r.pid,firstUnresponsiveAtEpochMs:r.firstUnresponsiveAtEpochMs}}catch{return null}}function ss(){let r=Do();if((0,k.existsSync)(r))try{(0,k.unlinkSync)(r)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function a_(r=Date.now()){let e=Qe()?.pid??null;if(e===null)return!1;let t=o_();if(t!==null&&t.pid===e)return r-t.firstUnresponsiveAtEpochMs>=Au;try{K(Do(),{pid:e,firstUnresponsiveAtEpochMs:r})}catch(n){f.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function Lo(){return F.default.join(re(),"worker-never-ready-recycle.json")}function c_(){try{let r=JSON.parse((0,k.readFileSync)(Lo(),"utf-8"));return typeof r?.buildKey!="string"||typeof r?.failureMessage!="string"?null:{buildKey:r.buildKey,failureMessage:r.failureMessage,refusalLogged:r.refusalLogged===!0}}catch{return null}}function Ru(r){try{K(Lo(),r)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function l_(){let r=Lo();if((0,k.existsSync)(r))try{(0,k.unlinkSync)(r)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function vu(r){return wu(r,r?.version??"unknown")??"unresolved-worker-bundle"}function Mu(r){return r.outcome==="failed"?r.detail??"unknown init failure":r.outcome}function Ou(r,e){if(r.outcome==="unresponsive"&&!a_())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:r.detail,wedgedAfterMs:Au}),!1;let t=Mu(r),n=c_();return n!==null&&n.buildKey===e&&n.failureMessage===t?(n.refusalLogged?f.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:t}):(f.error("SYSTEM","Worker keeps failing to start the same way after a recycle; not recycling again. Run `npx claude-mem doctor` and check the worker logs",{outcome:r.outcome,failureMessage:t,logsDir:F.default.join(re(),"logs")}),Ru({...n,refusalLogged:!0})),!1):!0}function Cu(r,e){Ru({buildKey:e,failureMessage:Mu(r)}),ss()}async function Iu(r=Number.POSITIVE_INFINITY){let e=r-Date.now();if(e<=0)return!1;let t;try{t=await Vh(Math.min(St,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return t}async function Pu(r,e){let t=Qe();if(t===null||t.port!==Ee())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:Ee(),pidFilePid:t?.pid??null,pidFilePort:t?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await he(t.pid,{signalMode:"immediate"})}catch(n){return f.error("SYSTEM","Could not kill stale worker",{pid:t.pid,port:t.port},n instanceof Error?n:new Error(String(n))),!1}return await s_(tt(5e3,r))?!0:(e("stale port release")||(Et=Ee(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:t.pid,port:Ee(),fix:os})),!1)}async function is(r){let e=r===void 0?null:Date.now()+r,t=h=>ns(e)?(f.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:h,budgetMs:r}),!0):!1,n=()=>e===null?void 0:tt(St,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),i=ko(),o=null,a=null,c=!1,l=null,u=null,d=Mn(Y());if(t("health probe"))return!1;if(await Iu(s)){if(t("version probe"))return!1;let{matches:h,pluginVersion:_,workerVersion:E}=await Hl(Ee(),i?.version??null,n());if(_!=="unknown"&&(o=_),h){if(t("readiness wait"))return!1;let y=await Bt(tt(Sr,e));if(y.outcome==="ready")return o!==null&&!ns(e)&&await lu(o,null,n()),!0;if(y.outcome==="still_booting"||y.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:y.outcome,detail:y.detail}),!1;if(d)return f.warn("SYSTEM","Worker will never become ready; CLAUDE_MEM_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:y.outcome,detail:y.detail}),!1;if(u=vu(i),!Ou(y,u))return!1;l=y,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:y.outcome,detail:y.detail,version:E})}else{if(d)return f.warn("SYSTEM","Worker version differs from the installed plugin; CLAUDE_MEM_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:_,workerVersion:E}),t("readiness wait")?!1:(await Bt(tt(Sr,e))).outcome==="ready";if(a=wu(i,_),i_(a,E))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:_,workerVersion:E,scriptPath:i?.scriptPath}),t("readiness wait")?!1:(await Bt(tt(Sr,e))).outcome==="ready";f.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:_,workerVersion:E})}if(!await Pu(e,t))return!1;l!==null&&u!==null&&Cu(l,u),c=!0}if(d)return f.debug("SYSTEM","Worker not running and CLAUDE_MEM_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let g=i?.scriptPath??null;if(t("lazy spawn"))return!1;let p=yo();try{if(p){if(!c&&!await u_(s,e))return!1;let _=mo();if(!_)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!g)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:_,scriptPath:g});try{if(_o(_,g,Le({...process.env,CLAUDE_MEM_WORKER_PORT:String(Ee())}),process.platform,Po(e)??void 0)===void 0)return!1}catch(E){return E instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:_,scriptPath:g},E):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:_,scriptPath:g,error:String(E)}),!1}}else f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await e_({attempts:6,backoffMs:500,deadlineAt:e}))return t("cold-boot port wait")||(f.warn("SYSTEM",p?"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)"),Qe()===null&&await Bl(Ee(),e===null?void 0:tt(5e3,e))&&(Et=Ee(),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:Et,fix:os}))),!1}finally{p&&bo()}if(t("readiness wait"))return!1;let m=await Bt(tt(Sr,e));return m.outcome!=="ready"?(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:m.outcome,detail:m.detail}),!1):(o!==null&&!ns(e)&&await lu(o,a,n()),!0)}var os="Set CLAUDE_MEM_WORKER_PORT to a different port in claude-mem settings, or reboot to release the stuck port",Et=null,vo=null;async function u_(r,e){let t=Ee(),n=r-Date.now();if(n<=0)return!1;let s=await Yn(t,n);if(s==="free")return!0;if(s==="unbindable")return vo=t,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:t,host:br(),fix:Eo}),!1;if(s==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:t}),!1;let i=await Zl(t,{deadlineAt:e});return i.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:t,killedPids:i.killedPids}),!0):(Qe()===null&&(Et=t),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:t,reclaimReason:i.reason,...Et===t?{fix:os}:{}}),!1)}var rs=null;async function d_(r){return rs!==null||(rs=await is(r)),rs}async function f_(r){let e=Date.now()+r,t=()=>e-Date.now(),n=l=>t()>=Mo?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:l,budgetMs:r}),!0),s=await Bt(Math.max(1,t()));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:r}),!1;if(!!Mn(Y()))return uu(e);let o=mo(),a=xo();if(!o||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let l=vu(ko());if(!Ou(s,l)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await Pu(e,n)))return!1;Cu(s,l)}let c=yo();try{return c&&_o(o,a,Le({...process.env,CLAUDE_MEM_WORKER_PORT:String(Ee())}),process.platform,Math.max(1,t()))===void 0?!1:await uu(e)}catch(l){return f.debug("SYSTEM","Bounded worker startup failed",{error:l instanceof Error?l.message:String(l)}),!1}finally{c&&bo()}}async function uu(r){for(;r-Date.now()>0;){let e=await Bt(Math.max(1,r-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 t=Math.min(100,r-Date.now());t>0&&await new Promise(n=>setTimeout(n,t))}return!1}var p_=3,ku=20,xu=1e3,g_=10,Du=5e3,m_=Du+xu;function as(){return F.default.join(U,"state")}function Lu(){return F.default.join(as(),"hook-failures.json")}function Nu(){return F.default.join(as(),"hook-failures.lock")}async function No(r=xu){let e=as(),t=Nu(),n=(0,gu.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),i=Date.now()+r;for(;Date.now()<=i;)try{return(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(t,s,{flag:"wx"}),n}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=a.code;if(c!=="EEXIST")return f.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:t,code:c},a),null;let l;try{l=(0,k.statSync)(t).mtimeMs}catch{continue}if(Date.now()-l>Du){let u;try{u=(0,k.statSync)(t).mtimeMs}catch{continue}if(u===l)try{(0,k.unlinkSync)(t);continue}catch{}}await new Promise(u=>setTimeout(u,g_))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:t,waitMs:r}),null}function Fo(r){let e=Nu();try{if(JSON.parse((0,k.readFileSync)(e,"utf-8")).token!==r)return;(0,k.unlinkSync)(e)}catch{}}function h_(r){let e=JSON.parse(r);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(t=>typeof t=="string").slice(-ku):void 0}}function yr(){try{return h_((0,k.readFileSync)(Lu(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Uo(r){let e=as(),t=Lu(),n=`${t}.tmp`;try{return(0,k.existsSync)(e)||(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,k.renameSync)(n,t),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function __(){try{let e=Y().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return p_}var du=null;function Fu(r){let e=vo!==null?`The worker cannot bind port ${vo} on ${br()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Eo}.`:Et!==null?`Port ${Et} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${os}.`:"Run `npx claude-mem restart`; if it keeps failing, run `npx claude-mem doctor`.";return`claude-mem worker unreachable for ${r} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${e}`}var E_=!1,fu=!1;async function Ro(){if(E_){if(fu)return yr().consecutiveFailures;fu=!0}let r=await No();if(r===null)return yr().consecutiveFailures;let e,t=!1;try{let n=yr();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=__();t=e.consecutiveFailures>=s&&!e.thresholdTripped,t&&(e.thresholdTripped=!0);let i=Uo(e);t=t&&i}finally{Fo(r)}return t&&(await Sl("hook_failed",{...du!==null?{hook_type:du}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),je(`${Fu(e.consecutiveFailures)}
23
+ `)),e.consecutiveFailures}async function Uu(r){if(!r)return null;let e=await No();if(e===null)return null;try{let t=yr(),n=t.notifiedSessionIds??[];return!t.thresholdTripped||n.includes(r)?null:Uo({...t,notifiedSessionIds:[...n,r].slice(-ku)})?Fu(t.consecutiveFailures):null}finally{Fo(e)}}async function pu(){let r=await No(m_);if(r!==null)try{let e=yr();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;Uo({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Fo(r)}}var _t=Symbol.for("claude-mem/worker-fallback");function $u(r){return typeof r=="object"&&r!==null&&r[_t]===!0}async function Bu(r,e,t,n={}){let s=Date.now(),i=n.workerStartupTimeoutMs!==void 0;if(!(i?await f_(n.workerStartupTimeoutMs):await d_(n.timeoutMs)))return Mn(Y())?{continue:!0,reason:"worker_autostart_disabled",[_t]:!0}:(i||await Ro(),{continue:!0,reason:"worker_unreachable",[_t]:!0});let a={method:e};if(t!==void 0&&(a.headers={"Content-Type":"application/json"},a.body=JSON.stringify(t)),n.timeoutMs!==void 0){let u=i?n.timeoutMs:n.timeoutMs-(Date.now()-s);if(u<Mo)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:r}),i||await Ro(),{continue:!0,reason:"worker_budget_exhausted",[_t]:!0};a.timeoutMs=u}let c;try{c=await Fe(r,a)}catch(u){if(!i)throw u;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:u instanceof Error?u.message:String(u)}),{continue:!0,reason:"worker_unreachable",[_t]:!0}}if(!c.ok){let u=await c.text().catch(()=>"");if(await pu(),c.status===429||c.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${r} returned ${c.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${c.status}`,[_t]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}let l;try{l=await c.text()}catch(u){return f.debug("SYSTEM","Worker response body could not be read; treating the worker as unreachable",{error:u instanceof Error?u.message:String(u)}),i||await Ro(),{continue:!0,reason:"worker_body_read_failed",[_t]:!0}}if(await pu(),l.length!==0)try{return JSON.parse(l)}catch{return l}}M();var Ue=require("path");W();var S_="plugins",y_="cache",b_="thedotmack",w_="claude-mem",T_="plugin",A_=(0,Ue.join)(ut,S_,y_,b_,w_),R_=(0,Ue.join)(Dt,T_);function $o(r,e){let t=(0,Ue.normalize)(r),n=(0,Ue.normalize)(e);if(t===n)return!0;let s=(0,Ue.relative)(n,t);return s.length>0&&!s.startsWith("..")&&!(0,Ue.isAbsolute)(s)}function cs(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if($o(r,wn)||$o(r,A_)||$o(r,R_))return!1;let e=Y();return!Kn(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Wu="claude";function v_(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function V(r){if(!r)return Wu;let e=v_(r);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:Wu}var M_=new Set(["claude","codex","cursor","kimi","antigravity-cli","gemini","opencode","openclaw","omp","pi","qwen","windsurf"]);function wr(r){if(!r||r==="unknown")return"unknown";let e=V(r);return M_.has(e)?e:"other"}function ls(r){if(r==="TodoWrite"||r==="SetTodoList"||r==="update_plan"||r==="functions.update_plan")return"native_todo";let e=r.replace(/^mcp__[^_].*?__/,"");return e==="work_state_write"?"write":e==="work_state_read"?"read":null}function Bo(r,e){if(typeof e=="string"){if(e.length<=32768&&e.trimStart().startsWith("{"))try{return Bo(r,JSON.parse(e))}catch{}return Hu(r,e.slice(0,1500),!1)}if(!e||typeof e!="object")return"unknown";let t=e,n=typeof t.error=="string"?t.error.slice(0,1500):Array.isArray(t.content)?t.content.slice(0,5).filter(s=>s&&s.type==="text"&&typeof s.text=="string").map(s=>s.text.slice(0,300)).join(`
24
+ `):"";return Hu(r,n,t.isError===!0||!!t.error)}function Hu(r,e,t){return e.includes("CLAUDE_MEM_WORK_STATE_ENABLED=false")?"disabled":e.startsWith("Not saved: this project is excluded")?"excluded":t||/^(?:Error:|Tool execution failed:|Error executing tool|(?:Worker|Server) request failed(?: \(HTTP \d+\))?\.)/.test(e)?"error":r==="write"?e.startsWith('Saved to "')?"ok":"unknown":r==="read"&&e?"ok":"unknown"}M();var fs=require("fs");M();W();le();var us=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,O_=`(?=${us}{8})${us}*[A-Za-z]${us}*`,ds=String.raw`(?:\\{0,3}["'])?`,Rr=String.raw`\s{0,8}`;function Wo(r){return new RegExp(`${r}${O_}`,"gi")}function ju(r){return`(?<=${r}${ds}${Rr}[=:]${Rr}${ds})`}var C_=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s{0,8}[=:]\s{0,8}['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],I_=[{name:"generic_password",regex:Wo(ju(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:Wo(ju(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:Wo(`(?<=\\bAuthorization${ds}${Rr}:${Rr}${ds}Bearer${Rr})`)}],P_=1024*1024,k_="<redacted type='oversize'/>";function zu(r,e){if(!e.enabled||r.length===0)return{redacted:r,counts:{},oversize:!1};if(r.length>P_)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:r.length}),{redacted:k_,counts:{oversize:1},oversize:!0};let t=new Set(e.disabledBuiltinPatterns??[]),n={},s=r,i=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){f.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{i.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){f.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let o=[...i,...C_,...e.genericEnabled?I_:[]];for(let a of o)t.has(a.name)||(a.regex.lastIndex=0,s=s.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function x_(r){if(!r||r.trim()==="")return[];try{let e=JSON.parse(r);return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"&&typeof t.regex=="string"):(f.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return f.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function D_(r){return{enabled:r.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(r.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:x_(r.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:r.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:r.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}var Tr=null,Ku=0,L_=5e3,Ar=null,Gu=!1,N_={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},F_=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function U_(r){if(!(0,fs.existsSync)(r))return null;try{return(0,fs.readFileSync)(r,"utf-8")}catch{return""}}function $_(r){if(r===null)return!1;try{let e=JSON.parse(xi(r));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function B_(r,e,t){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(Ar?.enabled===!0||F_.test(e))?t:(Gu||(Gu=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:r,using:Ar?.enabled?"the last configuration that loaded":"the built-in patterns"})),Ar?.enabled?Ar:N_)}function Vu(r=ne){let e=Date.now();if(Tr&&e-Ku<L_)return Tr;let t=H.loadFromFile(r),n=D_(t),s=n.enabled?null:U_(r);return $_(s)?Tr=B_(r,s,n):(Tr=n,Ar=n),Ku=e,Tr}var Fv=new RegExp(`^${us}{8,}$`);var Ho=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],W_=new Set(Ho),qu=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Yu=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;function H_(r){let e=Object.fromEntries(Ho.map(u=>[u,0]));if(!r.includes("<"))return{text:r,counts:e,total:0};let t=r.length,n=new Int32Array(t+1);n[t]=t;for(let u=t-1;u>=0;u--)n[u]=r.charCodeAt(u)===62?u:n[u+1];let s=new Map,i=[],o=0,a=0;for(;a<t;){if(r.charCodeAt(a)!==60){a+=1;continue}Yu.lastIndex=a;let u=Yu.exec(r);if(u){let g=u[1],p=s.get(g),m=p&&p.head<p.items.length?p.items[p.head]:void 0;m&&a>=m.attrEnd&&(p.head+=1,i.push([m.start,a+u[0].length]),e[g]+=1,o+=1),a+=u[0].length;continue}qu.lastIndex=a;let d=qu.exec(r);if(d&&W_.has(d[1])){let g=d[1],p=a+d[0].length,m={start:a,attrEnd:n[p]},h=s.get(g);h?h.items.push(m):s.set(g,{items:[m],head:0}),a=p;continue}a+=1}i.sort((u,d)=>u[0]-d[0]);let c="",l=0;for(let[u,d]of i)u>l&&(c+=r.slice(l,u)),d>l&&(l=d);return c+=r.slice(l),{text:c,counts:e,total:o}}var Ju=100;function j_(r){let{text:e,counts:t,total:n}=H_(r);return n>Ju&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:Ju,contentLength:r.length}),{stripped:zu(e.trim(),Vu()).redacted,counts:t}}function ps(r){return j_(r).stripped}var K_=new RegExp(`<(${Ho.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);function jo(r){let e=t=>typeof t=="string"?K_.test(t)?ps(t):t:Array.isArray(t)?t.map(e):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([n,s])=>[n,e(s)])):t;return e(r)}var G_=["task-notification"],z_=new RegExp(`^\\s*<(${G_.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),V_=256*1024;function Xu(r){return!r||r.length>V_?!1:z_.test(r)}var q_=[/^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/,/^This is an app-generated request for a suggested next user message\. The user did not write this message\./,/^Consolidate the supplied rollout summaries into `memory_summary\.md`/];function Qu(r){let e=r.trimStart();return q_.some(t=>t.test(e))}M();var Y_=xe(Q.API_REQUEST),Ge=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),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)}},ms=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=J_(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Y_}async startSession(e,t={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new Ge("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e,t={}){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=gs(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,t)}async getJobStatus(e){if(!e)throw new Ge("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:t,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:gs(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:gs(e.platformSource)}:{},...e.metadata!==void 0?{metadata:jo(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:gs(e.platformSource)}:{},...e.payload!==void 0?{payload:jo(e.payload)}:{}}}async request(e,t,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new Ge("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${t}`,o={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(o.body=JSON.stringify(n));let a=d=>{let g=d instanceof Error?d.message:String(d),p=/timed out|timeout/i.test(g)||d instanceof Error&&(d.name==="TimeoutError"||d.name==="AbortError");return new Ge(p?"timeout":"transport",`Server ${e} ${t} failed: ${g}`,{cause:d})},c,l=s.timeoutMs??this.timeoutMs;try{c=await Co(i,o,l)}catch(d){throw a(d)}if(!c.ok){let d=await c.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${t} returned ${c.status}: ${X_(d,200)}`,{status:c.status})}let u;try{u=await c.text()}catch(d){throw a(d)}if(!u||u.length===0)return{};try{return JSON.parse(u)}catch(d){let g=d instanceof Error?d:new Error(String(d));throw new Ge("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:g})}}};function hs(r){return r instanceof Ge}function J_(r){return r.replace(/\/+$/,"")}function gs(r){return typeof r=="string"?V(r):null}function X_(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Zu(){let e=(Y().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Q_(){let r=Y(),e=(...o)=>{for(let a of o){let c=(a??"").trim();if(c.length>0)return c}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),s=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new ms(i),projectId:s,serverBaseUrl:t}}function _s(){if(Zu()!=="server")return{runtime:"worker"};let r=Q_();return r||{runtime:"worker"}}function Es(r,e){f.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var Z_={executeWithWorkerFallback:Bu,getSessionInitRequestTimeoutMs:Su,isWorkerFallback:$u,consumeWorkerOutageNotice:Uu,loadFromFileOnce:Y,resolveRuntimeContext:_s,logServerFallback:Es,shouldTrackProject:cs,readHookEnvironment:()=>process.env},ve=Z_,eE=2,Ko=500,tE=2e3;var Ss=class extends Error{constructor(t){super(`session-init did not record the prompt (${t})`);this.reason=t;this.name="SessionPromptNotRecordedError"}reason};function rd(r){return sE.run(r,!0)}var rE=r=>r?r.replace(/\\/g,"/").includes("/.qwen/"):!1,nE=(r,e=process.env)=>r?e.QWEN_PROJECT_DIR?!0:rE(r):!1,sE={async run(r,e){let t=e?void 0:Date.now(),{sessionId:n,prompt:s,submittedPrompt:i}=r,o=r.cwd??process.cwd();if(!n)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};if(!ve.shouldTrackProject(o))return f.info("HOOK","Project excluded from tracking",{cwd:o}),{continue:!0,suppressOutput:!0};if(s&&Xu(s))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:s.slice(0,80)}),{continue:!0,suppressOutput:!0};if(s&&V(r.platform)==="codex"&&Qu(s))return f.debug("HOOK","session-init: skipping a Codex internal helper prompt",{reason:"internal_system_prompt",preview:s.slice(0,80)}),{continue:!0,suppressOutput:!0};if(i===null)return f.debug("HOOK","session-init: host reported no user-submitted text; not storing a prompt",{sessionId:n}),{continue:!0,suppressOutput:!0};if(i===void 0&&!s?.trim()&&nE(r.transcriptPath,ve.readHookEnvironment()))return f.debug("HOOK","session-init: Qwen send carried no submitted_prompt and no prompt text; not storing a prompt",{sessionId:n}),{continue:!0,suppressOutput:!0};let a=i??s,c=!a||!a.trim()?"[media prompt]":a,l=mt(o),u=l.primary,d=V(r.platform),g=ve.loadFromFileOnce(),p=String(g.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",m=ve.resolveRuntimeContext(),h=Date.now(),_=ve.getSessionInitRequestTimeoutMs();if(m.runtime==="server")try{return await iE(m,r,n,d,u,c,Math.max(Ko,Math.floor(_/eE))),{continue:!0,suppressOutput:!0}}catch(O){if(hs(O)&&O.isFallbackEligible())ve.logServerFallback(O.kind,{status:O.status,message:O.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:O instanceof Error?O.message:String(O)}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:n,project:u});let E=ed(h,_);if(E<Ko){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:n,project:u,remainingMs:E}),e)throw new Ss("budget_exhausted");return{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS}}let y=await ve.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:n,project:u,prompt:c,platformSource:d,telemetryPlatformSource:wr(r.platform),telemetryPromptEpochMs:t,agentId:r.agentId,agentType:r.agentType,cwd:o,projectKeySource:l.keySource},td(d,E));if(ve.isWorkerFallback(y)){if(e)throw new Ss("reason"in y?y.reason:"worker_fallback");let O=await ve.consumeWorkerOutageNotice(n);return{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS,...O?{systemMessage:O}:{}}}if(typeof y?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:n,project:u}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};let w=y.sessionDbId,R=y.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:w,promptNumber:R,skipped:y.skipped,contextInjected:y.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${n} | prompt#=${R} | sessionDbId=${w}`),y.skipped&&y.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${w} | promptNumber=${R} | skipped=true | reason=private`,{sessionId:w}),{continue:!0,suppressOutput:!0};let P="";if(p&&c&&c.length>=20&&c!=="[media prompt]"){let O=g.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",S=ed(h,_);if(S<Ko)f.warn("HOOK","session-init: skipping semantic injection because the prompt budget is spent",{contentSessionId:n,project:u,remainingMs:S});else{let T=await ve.executeWithWorkerFallback("/api/context/semantic","POST",{q:c,project:u,projects:l.allProjects,limit:O,format:g.CLAUDE_MEM_SEMANTIC_INJECT_FORMAT,platformSource:d},td(d,S));!ve.isWorkerFallback(T)&&T?.context&&(f.debug("HOOK",`Semantic injection: ${T.count} observations for prompt`,{sessionId:w,count:T.count}),P=T.context)}}return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${w} | promptNumber=${R} | project=${u}`,{sessionId:w}),P?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:P}}:{continue:!0,suppressOutput:!0}}};async function iE(r,e,t,n,s,i,o){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:i}},{timeoutMs:o}),f.info("HOOK","session-init: server session started",{contentSessionId:t,project:s})}function ed(r,e){return Math.max(0,e-(Date.now()-r))}function td(r,e){return r==="codex"?{workerStartupTimeoutMs:Q.POST_SPAWN_WAIT,timeoutMs:Math.min(tE,e)}:{timeoutMs:e}}var Wt=require("crypto"),L=require("fs"),pe=require("path");le();W();M();var oE=["observation","file_edit","summarize","session_end","advisor_calls","work_state_telemetry"];function aE(r){return`received_${r}`}var nd=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,od=/^[A-Za-z0-9_-]{1,128}$/,cE="corrupt",lE="expired",sd=10080*60*1e3,uE=300*1e3;function dE(){return(0,pe.join)(re(),"state","hook-spool")}function Ht(r){if(r===null||typeof r!="object")return JSON.stringify(r)??"null";if(Array.isArray(r))return`[${r.map(Ht).join(",")}]`;let e=r;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Ht(e[n])}`).join(",")}}`}function ad(r){return`remote_${r.kind}-${(0,Wt.createHash)("sha256").update(Ht(r)).digest("hex")}`}function id(r){return/^remote_[a-z_]+-[a-f0-9]{64}$/.test(r)}function fE(r,e){let t=e.toolUseId;return typeof t=="string"&&od.test(t)?`${(0,Wt.createHash)("sha256").update(e.contentSessionId).update("\0").update(V(e.platformSource)).digest("hex")}-${t}`:(0,Wt.createHash)("sha256").update(r).update("\0").update(e.contentSessionId).update("\0").update(Ht(e)).digest("hex")}function Go(r){return typeof r=="string"&&r.length>0}function ys(r){let e;try{e=JSON.parse(r)}catch(i){return{corruptReason:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}}if(e===null||typeof e!="object")return{corruptReason:"not an object"};let t=e;if(!oE.includes(t.kind))return{corruptReason:`unknown kind ${JSON.stringify(t.kind)}`};if(typeof t.enqueuedAtEpochMs!="number"||!Number.isFinite(t.enqueuedAtEpochMs))return{corruptReason:"missing enqueuedAtEpochMs"};let n=t.payload;if(n===null||typeof n!="object"||!Go(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=t.kind;return(s==="observation"||s==="file_edit")&&!Go(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"}:s==="work_state_telemetry"&&(!Go(n.eventId)||!["main","subagent","unknown",void 0].includes(n.agentRole)||(n.kind==="instruction"?!["returned","disabled","excluded","missing","unknown"].includes(String(n.state)):n.kind!=="mcp"||!["read","write"].includes(String(n.tool))||!["ok","error","excluded","disabled","unknown"].includes(String(n.outcome))))?{corruptReason:"invalid work-state telemetry shape"}:{kind:s,payload:{...n,platformSource:V(n.platformSource)},enqueuedAtEpochMs:t.enqueuedAtEpochMs}}var zo=0;function pE(){return zo=Math.max(Date.now(),zo+1),zo}var bs=class{constructor(e=dE()){this.directory=e}directory;get corruptDirectory(){return(0,pe.join)(this.directory,cE)}get expiredDirectory(){return(0,pe.join)(this.directory,lE)}enqueue(e,t,n){let s={...t,platformSource:V(t.platformSource)},i=(0,pe.join)(this.directory,`${e}-${fE(e,s)}.json`),o=s.toolUseId;if(typeof o=="string"&&od.test(o)){let c=(0,pe.join)(this.directory,`${e}-${o}.json`);try{let l=ys((0,L.readFileSync)(c,"utf8"));!("corruptReason"in l)&&l.kind===e&&l.payload.contentSessionId===s.contentSessionId&&l.payload.platformSource===s.platformSource&&(i=c)}catch{}}let a=this.existingEnqueuedAt(i)??n??pE();return K(i,{kind:e,payload:s,enqueuedAtEpochMs:a}),i}entries(){return this.readEntries().files.map(e=>e.entry)}hasEntries(){try{let e=(0,L.opendirSync)(this.directory);try{for(let t=e.readSync();t;t=e.readSync())if(t.isFile()&&nd.test(t.name))return!0}finally{e.closeSync()}}catch(e){["ENOENT","ENOTDIR"].includes(e.code??"")||f.warn("HOOK","Could not inspect pending hook spool files",{},e instanceof Error?e:new Error(String(e)))}return!1}enqueueRemote(e,t){let n=ad(e),s=aE(n);return!t.isConsumed(n)&&!t.isConsumed(s)&&(K((0,pe.join)(this.directory,`${n}.json`),e),t.markConsumed(s,Date.now())),n}async drain(e,t,n={}){let{files:s,quarantined:i,omitted:o}=this.readEntries(n.maxEntries),a=i,c=0,l=o,u=0;t?.pruneConsumedBefore(Date.now()-sd);let d=new Set;for(let[g,p]of s.entries()){if(n.shouldContinue&&!n.shouldContinue()){l+=s.length-g;break}let m=p.filename.replace(/\.json$/,"");if(t?.isConsumed(m)){f.info("HOOK","Hook spool entry was already handed to ingest before a restart; removing it without ingesting again",{kind:p.entry.kind,contentSessionId:p.entry.payload.contentSessionId,file:p.filename}),this.unlinkEntry(p)?(id(m)||t.clearConsumed(m),c++):l++;continue}let h=JSON.stringify([p.entry.payload.contentSessionId,p.entry.payload.platformSource]);if((p.entry.kind==="summarize"||p.entry.kind==="session_end")&&d.has(h)){l++;continue}let _=!1,E=()=>{if(!_){_=!0;try{t?.markConsumed(m,Date.now())}catch(w){f.error("HOOK","Could not record a hook spool hand-off marker; a crash before the file is removed would ingest it twice",{kind:p.entry.kind,contentSessionId:p.entry.payload.contentSessionId,file:p.filename},w instanceof Error?w:new Error(String(w)))}}},y;try{y=await e(p.entry,E)}catch(w){f.warn("HOOK",_?"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:p.entry.kind,contentSessionId:p.entry.payload.contentSessionId,file:p.filename},w instanceof Error?w:new Error(String(w))),y=!1}if(_&&(y=!0),y==="rejected"){this.unlinkTransferredEntry(p,"Remote worker permanently rejected this capture event")?a++:l++;continue}if(y==="expired"){this.expireIfPastWindow(p,uE,"unknown-session grace window")?u++:l++;continue}if(!y){this.expireIfPastWindow(p,sd,"retry window")?u++:((p.entry.kind==="observation"||p.entry.kind==="file_edit")&&d.add(h),l++);continue}this.unlinkEntry(p,n.verifyUnchanged)?(id(m)||t?.clearConsumed(m),c++):l++}return{drained:c,retained:l,quarantined:a,expired:u}}unlinkEntry(e,t=!1){if(t)return this.unlinkTransferredEntry(e);try{return(0,L.unlinkSync)(e.path),!0}catch(n){return n.code==="ENOENT"?!0:(f.warn("HOOK","Hook spool entry was ingested but could not be removed",{kind:e.entry.kind,file:e.filename},n instanceof Error?n:new Error(String(n))),!1)}}unlinkTransferredEntry(e,t){let n=(0,pe.join)(this.directory,`${e.entry.kind}-ack-${(0,Wt.randomBytes)(16).toString("hex")}.json`);try{(0,L.renameSync)(e.path,n)}catch(s){return s.code==="ENOENT"?!0:(f.warn("HOOK","Could not claim an acknowledged spool file; retaining it",{},s instanceof Error?s:new Error(String(s))),!1)}try{let s=ys((0,L.readFileSync)(n,"utf8"));if(!("corruptReason"in s)&&Ht(s)===Ht(e.entry))return t?((0,L.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,L.renameSync)(n,(0,pe.join)(this.corruptDirectory,e.filename)),f.error("HOOK",t,{file:e.filename,corruptDirectory:this.corruptDirectory})):(0,L.unlinkSync)(n),!0;try{(0,L.linkSync)(n,e.path),(0,L.unlinkSync)(n)}catch(i){i.code!=="EEXIST"&&f.warn("HOOK","Could not restore a replaced spool file; its claimed copy remains queued",{},i instanceof Error?i:new Error(String(i)))}}catch(s){f.warn("HOOK","Could not remove an acknowledged spool file; retaining it for retry",{},s instanceof Error?s:new Error(String(s)))}return!1}expireIfPastWindow(e,t,n){let s=Date.now()-e.entry.enqueuedAtEpochMs;if(s<=t)return!1;let i={kind:e.entry.kind,contentSessionId:e.entry.payload.contentSessionId,ageMinutes:Math.round(s/6e4),ageHours:Math.round(s/36e5),file:e.filename,expiredDirectory:this.expiredDirectory};try{(0,L.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,L.renameSync)(e.path,(0,pe.join)(this.expiredDirectory,e.filename))}catch(o){return f.error("HOOK",`Hook spool entry is past its ${n} but could not be moved to expired/; keeping it`,i,o instanceof Error?o:new Error(String(o))),!1}return f.error("HOOK",`Hook spool entry was never accepted within its ${n}; moved to expired/`,i),!0}existingEnqueuedAt(e){if(!(0,L.existsSync)(e))return null;try{let t=ys((0,L.readFileSync)(e,"utf-8"));return"corruptReason"in t?null:t.enqueuedAtEpochMs}catch(t){return f.debug("HOOK","Could not read existing hook spool entry; writing a fresh one",{entryPath:e},t instanceof Error?t:new Error(String(t))),null}}quarantine(e,t){let n=(0,pe.join)(this.directory,e);try{return(0,L.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,L.renameSync)(n,(0,pe.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:t,corruptDirectory:this.corruptDirectory}),!0}catch(s){return f.error("HOOK","Corrupt hook spool entry could not be quarantined; leaving it in place",{file:e,reason:t},s instanceof Error?s:new Error(String(s))),!1}}readEntries(e=Number.POSITIVE_INFINITY){if(!(0,L.existsSync)(this.directory))return{files:[],quarantined:0,omitted:0};let t;try{t=(0,L.readdirSync)(this.directory).filter(o=>nd.test(o))}catch(o){return f.warn("HOOK","Could not list hook spool entries",{directory:this.directory},o instanceof Error?o:new Error(String(o))),{files:[],quarantined:0,omitted:0}}let n=[],s=0,i=0;for(let o of t){let a=(0,pe.join)(this.directory,o),c;try{c=(0,L.readFileSync)(a,"utf-8")}catch(u){u.code!=="ENOENT"&&f.warn("HOOK","Could not read hook spool entry; will retry",{file:o},u instanceof Error?u:new Error(String(u)));continue}let l=ys(c);if("corruptReason"in l){this.quarantine(o,l.corruptReason)&&s++;continue}n.push({entry:l,path:a,filename:o}),n.length>e&&(n.sort((u,d)=>u.entry.enqueuedAtEpochMs-d.entry.enqueuedAtEpochMs||u.filename.localeCompare(d.filename)),n.pop(),i++)}return n.sort((o,a)=>o.entry.enqueuedAtEpochMs-a.entry.enqueuedAtEpochMs||o.filename.localeCompare(a.filename)),{files:n,quarantined:s,omitted:i}}};var fd=require("child_process"),pd=require("fs");W();var I=require("zod");var ld=1;var ws=I.z.object({contentSessionId:I.z.string().min(1).max(512),platformSource:I.z.string().min(1).max(128),cwd:I.z.string().max(32768).optional()}).passthrough(),cd=ws.extend({toolName:I.z.string().min(1).max(512),toolInput:I.z.unknown().optional(),toolResponse:I.z.unknown().optional(),toolUseId:I.z.string().max(2048).optional(),agentId:I.z.string().max(128).optional(),agentType:I.z.string().max(128).optional()}),jt=I.z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),gE=I.z.discriminatedUnion("kind",[I.z.object({kind:I.z.literal("observation"),payload:cd,enqueuedAtEpochMs:jt}),I.z.object({kind:I.z.literal("file_edit"),payload:cd,enqueuedAtEpochMs:jt}),I.z.object({kind:I.z.literal("summarize"),payload:ws.extend({lastAssistantMessage:I.z.string(),observedModel:I.z.string().max(1024).optional(),observedBilling:I.z.string().max(1024).optional()}),enqueuedAtEpochMs:jt}),I.z.object({kind:I.z.literal("session_end"),payload:ws,enqueuedAtEpochMs:jt}),I.z.object({kind:I.z.literal("advisor_calls"),payload:ws.extend({transcriptPath:I.z.string().max(32768).optional(),calls:I.z.array(I.z.object({toolUseId:I.z.string().min(1).max(2048),advice:I.z.string(),advisorModel:I.z.string().nullable().optional(),occurredAtEpoch:jt,lastUserMessage:I.z.string().nullable().optional(),transcriptByteOffset:I.z.number().int().nonnegative().nullable().optional()}).passthrough()).min(1).max(128)}),enqueuedAtEpochMs:jt})]),hM=I.z.object({protocolVersion:I.z.literal(ld),entry:gE}).strict();function ud(r){if(typeof r!="string")return"";let e=r.trim();return e.length<=1024&&/^[\x20-\x7e]+$/.test(e)?e:""}function dd(r,e="auto"){if(e=e.trim().toLowerCase(),e==="http")return!0;if(e==="filesystem"||!r)return!1;let t=r.toLowerCase().replace(/^\[|\]$/g,"");try{t=new URL(`http://${mr(r)}`).hostname.replace(/^\[|\]$/g,"")}catch{}return!(t==="localhost"||t.endsWith(".localhost")||t==="0.0.0.0"||t==="::"||t==="::1"||/^127\.\d+\.\d+\.\d+$/.test(t)||/^::ffff:127\.\d+\.\d+\.\d+$/.test(t)||/^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(t))}M();var mE=250,Ts=new Set,vr=null,hE=!1,Mr=null,Vo=!1,qo=!1;function gd(){if(Mr)return Mr;if(Vo)return qo=!0,Promise.resolve();let r=new Promise(e=>{setImmediate(()=>{try{_E()}catch{f.warn("HOOK","Remote hook uploader could not start; retaining the outbox")}finally{e()}})});return Mr=r,Ts.add(r),r.finally(()=>{Ts.delete(r),Mr===r&&(Mr=null)}),r}function _E(){if(!ud(Y().CLAUDE_MEM_WORKER_INGEST_TOKEN)){f.warn("HOOK","Remote hook capture is queued locally; configure CLAUDE_MEM_WORKER_INGEST_TOKEN on the client and worker");return}let e=process.argv[1],t=e&&/worker-service\.(?:cjs|ts)$/.test(e)&&(0,pd.existsSync)(e)?e:xo();if(!t){f.warn("HOOK","Remote hook upload entrypoint is unavailable; retaining the outbox");return}Vo=!0;let n=!1,s=()=>{n||(n=!0,Vo=!1,qo&&(qo=!1,gd()))};try{let i=(0,fd.spawn)(process.execPath,[t,"upload-spool"],{cwd:re(),env:Le(process.env),detached:!0,windowsHide:!0,stdio:"ignore"});i.once("error",()=>{f.warn("HOOK","Remote hook uploader could not start; retaining the outbox"),s()}),i.once("exit",o=>{o!==0&&f.warn("HOOK","Remote hook uploader exited unsuccessfully; retaining the outbox",{code:o}),s()}),i.unref()}catch{f.warn("HOOK","Remote hook uploader could not start; retaining the outbox"),s()}}function EE(){let r=Y();if(dd(br(),r.CLAUDE_MEM_HOOK_SPOOL_TRANSPORT))return hE=!0,gd();if(vr)return vr;let e=(async()=>{try{await(await Fe("/api/spool/nudge",{method:"POST",timeoutMs:mE})).body?.cancel()}catch(t){f.debug("HOOK","Hook spool nudge not delivered (worker will pick the entry up on its own)",{error:t instanceof Error?t.message:String(t)})}})();return vr=e,Ts.add(e),e.finally(()=>{Ts.delete(e),vr===e&&(vr=null)}),e}function Or(r,e){let t=new bs().enqueue(r,e);return f.debug("HOOK","Hook event spooled for the worker",{kind:r,entryPath:t}),EE(),t}M();function As(r,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(r.toLowerCase()):!1}var Yo="write_file",md={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:s}=r,i=V(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!cs(t))return f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};let o={filePath:n,edits:s},a={success:!0},c=_s();if(c.runtime==="server"){if(As(Yo,Y().CLAUDE_MEM_SKIP_TOOLS))return f.debug("HOOK","Server runtime: file edit excluded by CLAUDE_MEM_SKIP_TOOLS",{filePath:n}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS};let l={projectId:c.projectId,contentSessionId:e,platformSource:i,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:Yo,tool_input:o,tool_response:a,cwd:t,platformSource:i}};try{return await c.client.recordEvent(l),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),{continue:!0,suppressOutput:!0}}catch(u){if(hs(u)&&u.isFallbackEligible())Es(u.kind,{status:u.status,message:u.message,route:"/v1/events"});else return f.error("HOOK","Server file edit failed (non-recoverable)",{error:u instanceof Error?u.message:String(u)}),{continue:!0,suppressOutput:!0,exitCode:ke.SUCCESS}}}return Or("file_edit",{contentSessionId:e,platformSource:i,toolName:Yo,toolInput:o,toolResponse:a,cwd:t}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};W();M();var Me=require("fs"),Ir=require("path");M();le();M();W();var Cr="<claude-mem-context>",Rs="</claude-mem-context>";function hd(r){let e=r.indexOf(Cr);if(e===-1)return null;let t=r.indexOf(Rs,e+Cr.length);return t===-1?null:{start:r.lastIndexOf(Cr,t),end:t+Rs.length}}var nO=j.settings();function _d(r,e){let t=`${Cr}
25
25
  ${e}
26
26
  ${Rs}`;if(!r)return t;let n=hd(r);return n?r.substring(0,n.start)+t+r.substring(n.end):r+`
27
27
 
28
28
  ${t}`}le();M();function Ed(r,e){if(!r)return;let t=(0,Ir.resolve)(r);if(t.includes("/.git/")||t.includes("\\.git\\")||t.endsWith("/.git")||t.endsWith("\\.git"))return;let n=(0,Ir.dirname)(r);(0,Me.existsSync)(n)||(0,Me.mkdirSync)(n,{recursive:!0});let s="";(0,Me.existsSync)(r)&&(s=(0,Me.readFileSync)(r,"utf-8"));let i=`# Memory Context
29
29
 
30
- ${e}`,o=_d(s,i);try{let a=Sn(r);En((0,Ir.dirname)(a));let c=`${a}.tmp`;(0,Me.writeFileSync)(c,o),(0,Me.renameSync)(c,a)}catch(a){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:r},a instanceof Error?a:new Error(String(a)))}}M();function yE(r){let e=r.trim().replace(/^\$\.?/,"");if(!e)return[];let t=[],n=e.split(".");for(let s of n){let i=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=i.exec(s))!==null;)o[1]?t.push(o[1]):o[2]&&t.push(parseInt(o[2],10))}return t}function Pr(r,e){if(!e)return;let t=yE(e),n=r;for(let s of t){if(n==null)return;n=n[s]}return n}function Sd(r){return r==null||r===""}function yd(r,e){if(r.startsWith("$watch.")){let t=r.slice(7);return e.watch[t]}if(r.startsWith("$schema.")){let t=r.slice(8);return e.schema[t]}if(r.startsWith("$session.")){let t=r.slice(9);return e.session?e.session[t]:void 0}if(r==="$cwd")return e.watch.workspace;if(r==="$project")return e.watch.project}function jt(r,e,t){if(r!==void 0){if(typeof r=="string"){let n=yd(r,t);return n!==void 0?n:Pr(e,r)}if(r.coalesce&&Array.isArray(r.coalesce))for(let n of r.coalesce){let s=jt(n,e,t);if(!Sd(s))return s}if(r.path){let n=yd(r.path,t);if(n!==void 0)return n;let s=Pr(e,r.path);if(!Sd(s))return s}if(r.value!==void 0)return r.value;if(r.default!==void 0)return r.default}}function bd(r,e,t){let n={};if(!r)return n;for(let[s,i]of Object.entries(r))n[s]=jt(i,e,t);return n}function kr(r,e,t){if(!e)return!0;if(e.all!==void 0){if(!Array.isArray(e.all))return!1;for(let o of e.all)if(!kr(r,o,t))return!1}if(e.any!==void 0&&(!Array.isArray(e.any)||!e.any.some(o=>kr(r,o,t))))return!1;let n=e.path||t.eventTypePath||"type",s=n?Pr(r,n):void 0,i=s==null||s==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&s!==e.equals||e.not_equals!==void 0&&s===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(s)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(s)||e.contains!==void 0&&(typeof s!="string"||!s.includes(e.contains))||e.not_contains!==void 0&&typeof s=="string"&&s.includes(e.not_contains)||e.starts_with!==void 0&&(typeof s!="string"||!s.startsWith(e.starts_with))||e.not_starts_with!==void 0&&typeof s=="string"&&s.startsWith(e.not_starts_with))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(s??"")))return!1}catch(o){return f.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}M();function vs(r,e){return!!r&&!!e}var wd={skip:!1};function bE(r){return new Set((r??"").split(",").map(e=>e.trim()).filter(Boolean))}function Jo(r,e,t){return vs(r,e)?t.CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&bE(t.CLAUDE_MEM_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:wd:wd}W();M();var Ms=class{static checkUserPromptPrivacy(e,t,n,s,i,o){let a=e.getUserPrompt(t,n,i);return a===null?(f.warn("HOOK",`${s}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:t,promptNumber:n,...o}),{allow:!0,prompt:""}):a.trim()===""?(f.debug("HOOK",`Skipping ${s} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var Kt=require("path");function Ad(){let r=wE();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function wE(r=process.argv[1]?(0,Kt.dirname)(process.argv[1]):process.cwd(),e=Kt.sep==="\\"){let t=e?Td(r):r;return n=>{if(!n)return;let s=e?Td(n):n,{dir:i,base:o,ext:a}=Kt.posix.parse(s);(a===".js"||a===".mjs"||a===".cjs")&&(o=o.slice(0,-1*a.length));let c=decodeURIComponent(o);i||(i=".");let l=i.lastIndexOf("/node_modules");if(l>-1)return`${i.slice(l+14).replace(/\//g,".")}:${c}`;if(i.startsWith(t)){let u=i.slice(t.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function Td(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var q={};Tg(q,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>js,DOMExceptionCoercer:()=>ga,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Hr,ErrorCoercer:()=>Ur,ErrorEventCoercer:()=>ma,ErrorPropertiesBuilder:()=>Fr,EventCoercer:()=>ha,ExceptionStepsBuffer:()=>ya,ObjectCoercer:()=>Br,PrimitiveCoercer:()=>Wr,PromiseRejectionEventCoercer:()=>_a,ReduceableCache:()=>Ea,StringCoercer:()=>$r,chromeStackLineParser:()=>ua,createDefaultStackParser:()=>pa,createStackParser:()=>mf,geckoStackLineParser:()=>da,getInjectedReleaseId:()=>NS,getUtf8ByteLength:()=>_f,nodeStackLineParser:()=>lf,opera10StackLineParser:()=>of,opera11StackLineParser:()=>af,resolveExceptionStepsConfig:()=>Sa,reverseAndStripFrames:()=>gf,stripReservedExceptionStepFields:()=>xS,winjsStackLineParser:()=>sf});var de=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.AiCaptureQueue="ai_capture_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.PushRegistered="push_registered",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysInProgress="surveys_in_progress",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function rt(r){let e=[];return JSON.stringify(r,function(t,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 TE=Array.isArray,vd=Object.prototype,TO=vd.hasOwnProperty,Os=vd.toString,ge=TE||function(r){return Os.call(r)==="[object Array]"};var xr=r=>r===Object(r)&&!ge(r);var ze=r=>r===void 0,ee=r=>Os.call(r)=="[object String]",Xo=r=>ee(r)&&r.trim().length===0,Qo=r=>r===null,Oe=r=>ze(r)||Qo(r),Gt=r=>Os.call(r)=="[object Number]"&&r===r;var Md=r=>Os.call(r)==="[object Boolean]";function Cs(r){return r===null||typeof r!="object"}function yt(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function nt(r){switch(Object.prototype.toString.call(r)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Id(r,Error)}}function Od(r){return yt(r,"ErrorEvent")}function zt(r){return"u">typeof Event&&Id(r,Event)}function Cd(r){return yt(r,"Object")}function Id(r,e){try{return r instanceof e}catch{return!1}}var AE=["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"],Is=new Map,RE=256;function vE(r,e){let t="";for(let n=0;n<e.length;n++){let s=e[n];t+=s.length+":"+s}return r.length+":"+r+"|"+e.length+":"+t}var Pd=function(r,e=[]){if(!r)return!1;let t=vE(r,e),n=Is.get(t);if(n!==void 0)return n;let s=r.toLowerCase(),i=AE.concat(e).some(o=>s.indexOf(o.toLowerCase())!==-1);return Is.size>=RE&&Is.clear(),Is.set(t,i),i};function Dr(r,e,t,n,s){return e>t&&(n.warn("min cannot be greater than max."),e=t),Gt(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+s),Dr(s??t,e,t,n))}var ME=864e5,OE=1,CE=10;function kd(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??OE,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??CE}}var Ps=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Dr(e.bucketSize,0,100,e._logger),this._refillRate=Dr(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Dr(e.refillInterval,0,ME,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,s=Math.floor(n/this._refillInterval);if(s>0){let i=s*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),s=this._buckets[n];return s?this._applyRefill(s,t):(s={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=s),s.tokens===0?!0:(s.tokens--,s.tokens===0&&this._onBucketRateLimited?.(e),s.tokens===0)}stop(){this._buckets={}}};var ks="0123456789abcdef",xs=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>0xffffffffffff||t>4095||n>1073741823||s>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new r(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([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:t=/^\{([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:t=/^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(t){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let i=parseInt(t.substring(2*s,2*s+8),16);n[s+0]=i>>>24,n[s+1]=i>>>16,n[s+2]=i>>>8,n[s+3]=i}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=ks.charAt(this.bytes[t]>>>4),e+=ks.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=ks.charAt(this.bytes[t]>>>4),e+=ks.charAt(15&this.bytes[t]);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(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},Zo=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??IE()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return xs.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,xs.ofInner(e)}},IE=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),xd,ae=()=>PE().toString(),PE=()=>(xd||(xd=new Zo)).generate();var Ds=class{add(e){let t=ae(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(s=>s.id<=t&&!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 kE(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Dd=(r,e,t)=>{function n(i,...o){e(()=>{let a=t[i];a(r,...o)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{t.error(r,...i)},createLogger:i=>Dd(`${r} ${i}`,e,t)}},xE=r=>r();function Ld(r,e=xE){return Dd(r,e,kE())}var qt="Mobile",Ns="iOS",Vt="Android",Bd="Tablet",UO=Vt+" "+Bd;var LE="Apple",$O=LE+" Watch",Wd="Safari",Fs="BlackBerry",Hd="Samsung",NE=Hd+"Browser",FE=Hd+" Internet",Us="Chrome",UE=Us+" OS",$E=Us+" "+Ns,jd="Internet Explorer",BE=jd+" "+qt,ra="Opera",BO=ra+" Mini",Kd="Edge",WE="Microsoft "+Kd,na="Firefox",HE=na+" "+Ns,sa="Nintendo",ia="PlayStation",Ls="Xbox",jE=Vt+" "+qt,KE=qt+" "+Wd,Lr="Windows",GE=Lr+" Phone";var Gd="Generic",WO=Gd+" "+qt.toLowerCase(),HO=Gd+" "+Bd.toLowerCase(),zE="Konqueror",VE="Oculus Browser",Nd="Vivaldi",qE="Yandex",Fd="Whale",YE="DuckDuckGo",JE="Pale Moon",Ud="Waterfox",$d="Brave",zd="Claude",Vd="Codex",qd="ChatGPT",XE="Google Search App",$="(\\d+(\\.\\d+)?)",ea=new RegExp("Version/"+$),ta=new RegExp("("+zd+"|"+Vd+"|"+qd+")\\/"+$);var jO=new RegExp(Ls,"i"),KO=new RegExp(ia+" \\w+","i"),GO=new RegExp(sa+" \\w+","i"),QE=new RegExp(Fs+"|PlayBook|BB10","i"),ZE={"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 zO={[BE]:[new RegExp("rv:"+$)],[WE]:[new RegExp(Kd+"?\\/"+$)],[Us]:[new RegExp("("+Us+"|CrMo)\\/"+$)],[$E]:[new RegExp("CriOS\\/"+$)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$)],[Wd]:[ea],[KE]:[ea],[ra]:[new RegExp("("+ra+"|OPR)\\/"+$)],[na]:[new RegExp(na+"\\/"+$)],[HE]:[new RegExp("FxiOS\\/"+$)],[zE]:[new RegExp("Konqueror[:/]?"+$,"i")],[Fs]:[new RegExp(Fs+" "+$),ea],[jE]:[new RegExp("android\\s"+$,"i")],[FE]:[new RegExp(NE+"\\/"+$)],[VE]:[new RegExp("OculusBrowser\\/"+$)],[Nd]:[new RegExp(Nd+"\\/"+$)],[qE]:[new RegExp("YaBrowser\\/"+$)],[Fd]:[new RegExp(Fd+"\\/"+$)],[$d]:[new RegExp($d+"\\/"+$)],[zd]:[ta],[Vd]:[ta],[qd]:[ta],[YE]:[new RegExp("(DuckDuckGo|Ddg)\\/"+$)],[JE]:[new RegExp("PaleMoon\\/"+$)],[Ud]:[new RegExp(Ud+"\\/"+$)],[XE]:[new RegExp("GSA\\/"+$)],[jd]:[new RegExp("(rv:|MSIE )"+$)],Mozilla:[new RegExp("rv:"+$)]};var VO=[[new RegExp(Ls+"; "+Ls+" (.*?)[);]","i"),r=>[Ls,r&&r[1]||""]],[new RegExp(sa,"i"),[sa,""]],[new RegExp(ia,"i"),[ia,""]],[QE,[Fs,""]],[new RegExp(Lr,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[GE,""];if(new RegExp(qt).test(e)&&!/IEMobile\b/.test(e))return[Lr+" "+qt,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],s=ZE[n]||"";return/arm/i.test(e)&&(s="RT"),[Lr,s]}return[Lr,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[Ns,e.join(".")]}return[Ns,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=ze(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+Vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Vt+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[Vt,e.join(".")]}return[Vt,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[UE,""]],[/Linux|debian/i,["Linux",""]]];var $s="[Circular]",Bs="[Truncated]",Se="[Unserializable]",Yd="[Function]",JO=Date.prototype.getTime,XO=Date.prototype.toISOString;function $e(r){let e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(n>=55296&&n<=56319){let s=r.charCodeAt(t+1);s>=56320&&s<=57343?(e+=r[t]+r[t+1],t++):e+="\uFFFD"}else e+=n>=56320&&n<=57343?"\uFFFD":r[t]}return e}function Ve(r,e){if(!e)return r;let t=[];try{t=Object.keys(e)}catch{t=[]}for(let n of t){let s;try{s=e[n]}catch{s=Se}Object.defineProperty(r,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return r}function oa(r,e=Date.now()){if(typeof r!="string"||!r)return;let t=r.trim(),n=/^\d+\s*,/.test(t)?t.slice(0,t.indexOf(",")).trim():t;if(/^\d+$/.test(n)){let o=1e3*Math.min(Number(n),300);return o>0?o:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let s=/^\w{3} \w{3} /.test(n)?n+" GMT":n,i=Date.parse(s)-e;if(!(!Number.isFinite(i)||i<=0))return Math.min(i,3e5)}var bt=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),n=Date.now(),s=Math.min(e.retryAfterMs,3e5);if(!t){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 t=Math.min(3e5,Math.max(0,this._until-e));return t===0&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var Jd="utf8",eS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tS(r){return typeof r=="string"&&eS.test(r)}function wt(r,e){return tS(r)?r:e()}function Yt(r,e){let t=new Error(e);try{Object.defineProperty(t,"name",{value:r,writable:!0,enumerable:!0,configurable:!0})}catch{}return t}function Xd(r){return r?.replace(/\/+$/,"")}async function Qd(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await r()}catch(s){if(t=s,!e.retryCheck(s))throw s}}throw t}function aa(){return new Date().toISOString()}function ce(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}async function st(r,e,t){let n;try{return await Promise.race([r,new Promise((s,i)=>{n=ce(()=>{try{t?.(),s()}catch(o){i(o)}},e)})])}finally{clearTimeout(n)}}var Zd=r=>r&&typeof r.then=="function";function Nr(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var ca,ef,tf,Jt;function nf(r){let e=globalThis._posthogChunkIds,t=globalThis._debugIds;if(!e&&!t)return;let n=e?Object.keys(e):[],s=t?Object.keys(t):[];if(Jt&&rf(e,n,ef)&&rf(t,s,tf))return Jt;ef=e?{...e}:void 0,tf=t?{...t}:void 0,Jt={},ca??={};let i=(o,a)=>{for(let c of o){let l=a[c];if(!l)continue;let u=ca?.[c];if(u){Jt[u]=l;continue}let d=r(c);for(let g=d.length-1;g>=0;g--){let p=d[g]?.filename;if(p){Jt[p]=l,ca[c]=p;break}}}};return t&&i(s,t),e&&i(n,e),Jt}function rf(r,e,t){return!r||!t?r===t:e.length===Object.keys(t).length&&e.every(n=>r[n]===t[n])}var la=50,rS=1e3,nS=100,sS=4,Fr=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(s,t,0).apply(e),a=this.buildParsingContext(t),c=this.parseStacktrace(o,a);return{$exception_list:this.convertToExceptionList(c,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&ge(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:n,stack:s,errors:e.errors?.map(i=>this.parseStacktrace(i,t))}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n=[],s=(i,o,a)=>{let c=n.length,l=o===void 0?{type:typeof t.type=="string"&&t.type.length>0?t.type:"generic",...typeof t.handled=="boolean"?{handled:t.handled}:t.handled===void 0?{handled:!0}:{},synthetic:typeof t.synthetic=="boolean"?t.synthetic:i.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:i.synthetic,exception_id:c,parent_id:o},u={type:i.type,value:i.value,mechanism:l};i.stack&&(u.stacktrace={type:"raw",frames:i.stack}),n.push(u),i.cause&&s(i.cause,c,"cause");for(let d of i.errors??[])s(d,c,"member")};return s(e),n}buildParsingContext(e){return{chunkIdMap:nf(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(nt(e)){let t=Object.getPrototypeOf(e);for(let n=0;t&&n<nS;n++){let s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let i=e.errors;return ge(i)?i:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,n=0){let s=0,i=0,o=!1,a=new Set,c=[],l={},u=(p,m,h=0)=>{let _=d(m,h),E=_.apply;if(_.apply=S=>{c.push(p);try{return E(S)}finally{c.pop()}},h>sS||h>0&&c.indexOf(p)!==-1)return this.coerceFallback(_);let y=typeof p=="object"&&p!==null||typeof p=="function";if(h===0&&s>=la||y&&a.has(p))return;y&&a.add(p),h===0&&s++;let w=this.getAggregateErrors(p);o||=!!w;let R;try{if(R=this.applyCoercers(p,_),!R)throw l}catch(S){if(S===l){h===0&&s--;return}if(!o)throw S;R=this.coerceFallback(_)}if(!w||s>=la)return R;let P;try{P=w.length}catch{return R}if(!Number.isInteger(P)||P<0||P>4294967295)return R;let O=[];for(let S=0;s<la&&i<rS&&S<P;S++){i++;let T;try{T=_.next(w[S])}catch{s++,T=this.coerceFallback(d(m+1))}T&&O.push(T)}return{...R,errors:O}},d=(p,m=0)=>({...t,syntheticException:p==0?t.syntheticException:void 0,mechanism:p==0?e:{},apply:h=>{let _=u(h,p,m+1);if(!_)throw l;return _},next:h=>u(h,p+1)}),g=d(n);return{...g,apply:p=>u(p,n)??this.coerceFallback(g)}}};var X="?",iS="<anonymous>",oS=/^([a-z][a-z0-9.+-]+):/i,aS=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function cS(r){if(!r||r===iS)return!1;let e=oS.exec(r);return!e||aS.includes(e[1].toLowerCase())}function Be(r,e,t,n,s){let i={platform:r,filename:e,function:t==="<anonymous>"?X:t,in_app:cS(e)};return ze(n)||(i.lineno=n),ze(s)||(i.colno=s),i}var Ws=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:X,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var lS=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,uS=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dS=/\((\S*)(?::(\d+))(?::(\d+))\)/,ua=(r,e)=>{let t=lS.exec(r);if(t){let[,s,i,o]=t;return Be(e,s,X,+i,+o)}let n=uS.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=dS.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,o]=Ws(n[1]||X,n[2]);return Be(e,o,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var fS=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pS=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,da=(r,e)=>{let t=fS.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let o=pS.exec(t[3]);o&&(t[1]=t[1]||"eval",t[3]=o[1],t[4]=o[2],t[5]="")}let s=t[3],i=t[1]||X;return[i,s]=Ws(i,s),Be(e,s,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var gS=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,sf=(r,e)=>{let t=gS.exec(r);return t?Be(e,t[2],t[1]||X,+t[3],t[4]?+t[4]:void 0):void 0};var mS=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,of=(r,e)=>{let t=mS.exec(r);return t?Be(e,t[2],t[3]||X,+t[1]):void 0},hS=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,af=(r,e)=>{let t=hS.exec(r);return t?Be(e,t[5],t[3]||t[4]||X,+t[1],+t[2]):void 0};var _S=/^\s*[-]{4,}$/,ES=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,SS=/^Promise\.(?:all|any)$/,yS=/^index \d+$/,bS="node:internal/promise",lf=(r,e)=>{let t=r.match(ES);if(t){let n,s,i,o,a;if(t[1]){i=t[1];let u=i.lastIndexOf(".");if(i[u-1]==="."&&u--,u>0){n=i.slice(0,u),s=i.slice(u+1);let d=n.indexOf(".Module");d>0&&(i=i.slice(d+1),n=n.slice(0,d))}o=void 0}s&&(o=n,a=s),s==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||X,i=o?`${o}.${a}`:a);let c=t[2]?.startsWith("file://")?t[2].slice(7):t[2],l=t[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&t[5]&&!l&&(c=t[5]),SS.test(i)&&yS.test(c||"")&&(c=bS),{filename:c?decodeURI(c):void 0,module:void 0,function:i,lineno:cf(t[3]),colno:cf(t[4]),in_app:wS(c||"",l),platform:e}}if(r.match(_S))return{filename:r,platform:e}};function wS(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function cf(r){return parseInt(r||"",10)||void 0}var uf=/\(error: (.*)\)/,df=50,TS=10,AS=1e3;function fa(r,e){return r.filename===e.filename&&r.function===e.function&&r.module===e.module&&r.lineno===e.lineno&&r.colno===e.colno}function RS(r){for(let e=1;e<=TS;e++){let t=r.length-2*e;if(t<0)break;let n=!0;for(let s=0;s<e;s++){let i=r[t+s];if(!fa(i,r[t+e+s])){n=!1;break}}if(n){for(let s=0;s<e;s++)r[t+s]=r[t+e+s];return r.length=t+e,{start:t,length:e}}}}function vS(r,e){let t=e.start+e.length,n=pf(r,e);n&&r.splice(t+n===r.length?t:e.start,n)}function ff(r,e){let t=e.start;for(;t>0&&fa(r[t-1],r[t-1+e.length]);)t--;return e.start-t}function pf(r,e){let t=e.start+e.length,n=t;for(;n<r.length&&fa(r[n],r[n-e.length]);)n++;return n-t}function MS(r,e){let t=e[0],n=r.length-(t?ff(r,t):0);for(let s of e)n-=pf(r,s);return n}function OS(r){let e=r.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),t=0;for(let n=1;n<e.length;n++)CS(e,n,t)&&(t=n);r.push(...r.splice(0,t))}function CS(r,e,t){for(let n=0;n<r.length;n++){let s=r[(e+n)%r.length],i=r[(t+n)%r.length];if(s!==i)return s<i}return!1}function gf(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,df).map(t=>({...t,filename:t.filename||IS(e).filename,function:t.function||X}))}function IS(r){return r[r.length-1]||{}}function pa(){return mf("web:javascript",ua,da)}function mf(r,...e){return(t,n=0)=>{let s=[],i=t.split(`
30
+ ${e}`,o=_d(s,i);try{let a=Sn(r);En((0,Ir.dirname)(a));let c=`${a}.tmp`;(0,Me.writeFileSync)(c,o),(0,Me.renameSync)(c,a)}catch(a){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:r},a instanceof Error?a:new Error(String(a)))}}M();function yE(r){let e=r.trim().replace(/^\$\.?/,"");if(!e)return[];let t=[],n=e.split(".");for(let s of n){let i=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=i.exec(s))!==null;)o[1]?t.push(o[1]):o[2]&&t.push(parseInt(o[2],10))}return t}function Pr(r,e){if(!e)return;let t=yE(e),n=r;for(let s of t){if(n==null)return;n=n[s]}return n}function Sd(r){return r==null||r===""}function yd(r,e){if(r.startsWith("$watch.")){let t=r.slice(7);return e.watch[t]}if(r.startsWith("$schema.")){let t=r.slice(8);return e.schema[t]}if(r.startsWith("$session.")){let t=r.slice(9);return e.session?e.session[t]:void 0}if(r==="$cwd")return e.watch.workspace;if(r==="$project")return e.watch.project}function Kt(r,e,t){if(r!==void 0){if(typeof r=="string"){let n=yd(r,t);return n!==void 0?n:Pr(e,r)}if(r.coalesce&&Array.isArray(r.coalesce))for(let n of r.coalesce){let s=Kt(n,e,t);if(!Sd(s))return s}if(r.path){let n=yd(r.path,t);if(n!==void 0)return n;let s=Pr(e,r.path);if(!Sd(s))return s}if(r.value!==void 0)return r.value;if(r.default!==void 0)return r.default}}function bd(r,e,t){let n={};if(!r)return n;for(let[s,i]of Object.entries(r))n[s]=Kt(i,e,t);return n}function kr(r,e,t){if(!e)return!0;if(e.all!==void 0){if(!Array.isArray(e.all))return!1;for(let o of e.all)if(!kr(r,o,t))return!1}if(e.any!==void 0&&(!Array.isArray(e.any)||!e.any.some(o=>kr(r,o,t))))return!1;let n=e.path||t.eventTypePath||"type",s=n?Pr(r,n):void 0,i=s==null||s==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&s!==e.equals||e.not_equals!==void 0&&s===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(s)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(s)||e.contains!==void 0&&(typeof s!="string"||!s.includes(e.contains))||e.not_contains!==void 0&&typeof s=="string"&&s.includes(e.not_contains)||e.starts_with!==void 0&&(typeof s!="string"||!s.startsWith(e.starts_with))||e.not_starts_with!==void 0&&typeof s=="string"&&s.startsWith(e.not_starts_with))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(s??"")))return!1}catch(o){return f.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}M();function vs(r,e){return!!r&&!!e}var wd={skip:!1};function bE(r){return new Set((r??"").split(",").map(e=>e.trim()).filter(Boolean))}function Jo(r,e,t){return vs(r,e)?t.CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&bE(t.CLAUDE_MEM_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:wd:wd}W();M();var Ms=class{static checkUserPromptPrivacy(e,t,n,s,i,o){let a=e.getUserPrompt(t,n,i);return a===null?(f.warn("HOOK",`${s}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:t,promptNumber:n,...o}),{allow:!0,prompt:""}):a.trim()===""?(f.debug("HOOK",`Skipping ${s} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var Gt=require("path");function Ad(){let r=wE();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function wE(r=process.argv[1]?(0,Gt.dirname)(process.argv[1]):process.cwd(),e=Gt.sep==="\\"){let t=e?Td(r):r;return n=>{if(!n)return;let s=e?Td(n):n,{dir:i,base:o,ext:a}=Gt.posix.parse(s);(a===".js"||a===".mjs"||a===".cjs")&&(o=o.slice(0,-1*a.length));let c=decodeURIComponent(o);i||(i=".");let l=i.lastIndexOf("/node_modules");if(l>-1)return`${i.slice(l+14).replace(/\//g,".")}:${c}`;if(i.startsWith(t)){let u=i.slice(t.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function Td(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var q={};Tg(q,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>js,DOMExceptionCoercer:()=>ga,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Hr,ErrorCoercer:()=>Ur,ErrorEventCoercer:()=>ma,ErrorPropertiesBuilder:()=>Fr,EventCoercer:()=>ha,ExceptionStepsBuffer:()=>ya,ObjectCoercer:()=>Br,PrimitiveCoercer:()=>Wr,PromiseRejectionEventCoercer:()=>_a,ReduceableCache:()=>Ea,StringCoercer:()=>$r,chromeStackLineParser:()=>ua,createDefaultStackParser:()=>pa,createStackParser:()=>mf,geckoStackLineParser:()=>da,getInjectedReleaseId:()=>NS,getUtf8ByteLength:()=>_f,nodeStackLineParser:()=>lf,opera10StackLineParser:()=>of,opera11StackLineParser:()=>af,resolveExceptionStepsConfig:()=>Sa,reverseAndStripFrames:()=>gf,stripReservedExceptionStepFields:()=>xS,winjsStackLineParser:()=>sf});var de=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.AiCaptureQueue="ai_capture_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.PushRegistered="push_registered",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysInProgress="surveys_in_progress",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function rt(r){let e=[];return JSON.stringify(r,function(t,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 TE=Array.isArray,vd=Object.prototype,TO=vd.hasOwnProperty,Os=vd.toString,ge=TE||function(r){return Os.call(r)==="[object Array]"};var xr=r=>r===Object(r)&&!ge(r);var ze=r=>r===void 0,ee=r=>Os.call(r)=="[object String]",Xo=r=>ee(r)&&r.trim().length===0,Qo=r=>r===null,Oe=r=>ze(r)||Qo(r),zt=r=>Os.call(r)=="[object Number]"&&r===r;var Md=r=>Os.call(r)==="[object Boolean]";function Cs(r){return r===null||typeof r!="object"}function yt(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function nt(r){switch(Object.prototype.toString.call(r)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Id(r,Error)}}function Od(r){return yt(r,"ErrorEvent")}function Vt(r){return"u">typeof Event&&Id(r,Event)}function Cd(r){return yt(r,"Object")}function Id(r,e){try{return r instanceof e}catch{return!1}}var AE=["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"],Is=new Map,RE=256;function vE(r,e){let t="";for(let n=0;n<e.length;n++){let s=e[n];t+=s.length+":"+s}return r.length+":"+r+"|"+e.length+":"+t}var Pd=function(r,e=[]){if(!r)return!1;let t=vE(r,e),n=Is.get(t);if(n!==void 0)return n;let s=r.toLowerCase(),i=AE.concat(e).some(o=>s.indexOf(o.toLowerCase())!==-1);return Is.size>=RE&&Is.clear(),Is.set(t,i),i};function Dr(r,e,t,n,s){return e>t&&(n.warn("min cannot be greater than max."),e=t),zt(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+s),Dr(s??t,e,t,n))}var ME=864e5,OE=1,CE=10;function kd(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??OE,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??CE}}var Ps=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Dr(e.bucketSize,0,100,e._logger),this._refillRate=Dr(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Dr(e.refillInterval,0,ME,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,s=Math.floor(n/this._refillInterval);if(s>0){let i=s*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),s=this._buckets[n];return s?this._applyRefill(s,t):(s={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=s),s.tokens===0?!0:(s.tokens--,s.tokens===0&&this._onBucketRateLimited?.(e),s.tokens===0)}stop(){this._buckets={}}};var ks="0123456789abcdef",xs=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>0xffffffffffff||t>4095||n>1073741823||s>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new r(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([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:t=/^\{([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:t=/^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(t){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let i=parseInt(t.substring(2*s,2*s+8),16);n[s+0]=i>>>24,n[s+1]=i>>>16,n[s+2]=i>>>8,n[s+3]=i}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=ks.charAt(this.bytes[t]>>>4),e+=ks.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=ks.charAt(this.bytes[t]>>>4),e+=ks.charAt(15&this.bytes[t]);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(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},Zo=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??IE()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return xs.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,xs.ofInner(e)}},IE=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),xd,ae=()=>PE().toString(),PE=()=>(xd||(xd=new Zo)).generate();var Ds=class{add(e){let t=ae(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(s=>s.id<=t&&!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 kE(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Dd=(r,e,t)=>{function n(i,...o){e(()=>{let a=t[i];a(r,...o)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{t.error(r,...i)},createLogger:i=>Dd(`${r} ${i}`,e,t)}},xE=r=>r();function Ld(r,e=xE){return Dd(r,e,kE())}var Yt="Mobile",Ns="iOS",qt="Android",Bd="Tablet",UO=qt+" "+Bd;var LE="Apple",$O=LE+" Watch",Wd="Safari",Fs="BlackBerry",Hd="Samsung",NE=Hd+"Browser",FE=Hd+" Internet",Us="Chrome",UE=Us+" OS",$E=Us+" "+Ns,jd="Internet Explorer",BE=jd+" "+Yt,ra="Opera",BO=ra+" Mini",Kd="Edge",WE="Microsoft "+Kd,na="Firefox",HE=na+" "+Ns,sa="Nintendo",ia="PlayStation",Ls="Xbox",jE=qt+" "+Yt,KE=Yt+" "+Wd,Lr="Windows",GE=Lr+" Phone";var Gd="Generic",WO=Gd+" "+Yt.toLowerCase(),HO=Gd+" "+Bd.toLowerCase(),zE="Konqueror",VE="Oculus Browser",Nd="Vivaldi",qE="Yandex",Fd="Whale",YE="DuckDuckGo",JE="Pale Moon",Ud="Waterfox",$d="Brave",zd="Claude",Vd="Codex",qd="ChatGPT",XE="Google Search App",$="(\\d+(\\.\\d+)?)",ea=new RegExp("Version/"+$),ta=new RegExp("("+zd+"|"+Vd+"|"+qd+")\\/"+$);var jO=new RegExp(Ls,"i"),KO=new RegExp(ia+" \\w+","i"),GO=new RegExp(sa+" \\w+","i"),QE=new RegExp(Fs+"|PlayBook|BB10","i"),ZE={"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 zO={[BE]:[new RegExp("rv:"+$)],[WE]:[new RegExp(Kd+"?\\/"+$)],[Us]:[new RegExp("("+Us+"|CrMo)\\/"+$)],[$E]:[new RegExp("CriOS\\/"+$)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$)],[Wd]:[ea],[KE]:[ea],[ra]:[new RegExp("("+ra+"|OPR)\\/"+$)],[na]:[new RegExp(na+"\\/"+$)],[HE]:[new RegExp("FxiOS\\/"+$)],[zE]:[new RegExp("Konqueror[:/]?"+$,"i")],[Fs]:[new RegExp(Fs+" "+$),ea],[jE]:[new RegExp("android\\s"+$,"i")],[FE]:[new RegExp(NE+"\\/"+$)],[VE]:[new RegExp("OculusBrowser\\/"+$)],[Nd]:[new RegExp(Nd+"\\/"+$)],[qE]:[new RegExp("YaBrowser\\/"+$)],[Fd]:[new RegExp(Fd+"\\/"+$)],[$d]:[new RegExp($d+"\\/"+$)],[zd]:[ta],[Vd]:[ta],[qd]:[ta],[YE]:[new RegExp("(DuckDuckGo|Ddg)\\/"+$)],[JE]:[new RegExp("PaleMoon\\/"+$)],[Ud]:[new RegExp(Ud+"\\/"+$)],[XE]:[new RegExp("GSA\\/"+$)],[jd]:[new RegExp("(rv:|MSIE )"+$)],Mozilla:[new RegExp("rv:"+$)]};var VO=[[new RegExp(Ls+"; "+Ls+" (.*?)[);]","i"),r=>[Ls,r&&r[1]||""]],[new RegExp(sa,"i"),[sa,""]],[new RegExp(ia,"i"),[ia,""]],[QE,[Fs,""]],[new RegExp(Lr,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[GE,""];if(new RegExp(Yt).test(e)&&!/IEMobile\b/.test(e))return[Lr+" "+Yt,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],s=ZE[n]||"";return/arm/i.test(e)&&(s="RT"),[Lr,s]}return[Lr,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[Ns,e.join(".")]}return[Ns,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=ze(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+qt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+qt+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[qt,e.join(".")]}return[qt,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[UE,""]],[/Linux|debian/i,["Linux",""]]];var $s="[Circular]",Bs="[Truncated]",Se="[Unserializable]",Yd="[Function]",JO=Date.prototype.getTime,XO=Date.prototype.toISOString;function $e(r){let e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(n>=55296&&n<=56319){let s=r.charCodeAt(t+1);s>=56320&&s<=57343?(e+=r[t]+r[t+1],t++):e+="\uFFFD"}else e+=n>=56320&&n<=57343?"\uFFFD":r[t]}return e}function Ve(r,e){if(!e)return r;let t=[];try{t=Object.keys(e)}catch{t=[]}for(let n of t){let s;try{s=e[n]}catch{s=Se}Object.defineProperty(r,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return r}function oa(r,e=Date.now()){if(typeof r!="string"||!r)return;let t=r.trim(),n=/^\d+\s*,/.test(t)?t.slice(0,t.indexOf(",")).trim():t;if(/^\d+$/.test(n)){let o=1e3*Math.min(Number(n),300);return o>0?o:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let s=/^\w{3} \w{3} /.test(n)?n+" GMT":n,i=Date.parse(s)-e;if(!(!Number.isFinite(i)||i<=0))return Math.min(i,3e5)}var bt=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),n=Date.now(),s=Math.min(e.retryAfterMs,3e5);if(!t){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 t=Math.min(3e5,Math.max(0,this._until-e));return t===0&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var Jd="utf8",eS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tS(r){return typeof r=="string"&&eS.test(r)}function wt(r,e){return tS(r)?r:e()}function Jt(r,e){let t=new Error(e);try{Object.defineProperty(t,"name",{value:r,writable:!0,enumerable:!0,configurable:!0})}catch{}return t}function Xd(r){return r?.replace(/\/+$/,"")}async function Qd(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await r()}catch(s){if(t=s,!e.retryCheck(s))throw s}}throw t}function aa(){return new Date().toISOString()}function ce(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}async function st(r,e,t){let n;try{return await Promise.race([r,new Promise((s,i)=>{n=ce(()=>{try{t?.(),s()}catch(o){i(o)}},e)})])}finally{clearTimeout(n)}}var Zd=r=>r&&typeof r.then=="function";function Nr(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var ca,ef,tf,Xt;function nf(r){let e=globalThis._posthogChunkIds,t=globalThis._debugIds;if(!e&&!t)return;let n=e?Object.keys(e):[],s=t?Object.keys(t):[];if(Xt&&rf(e,n,ef)&&rf(t,s,tf))return Xt;ef=e?{...e}:void 0,tf=t?{...t}:void 0,Xt={},ca??={};let i=(o,a)=>{for(let c of o){let l=a[c];if(!l)continue;let u=ca?.[c];if(u){Xt[u]=l;continue}let d=r(c);for(let g=d.length-1;g>=0;g--){let p=d[g]?.filename;if(p){Xt[p]=l,ca[c]=p;break}}}};return t&&i(s,t),e&&i(n,e),Xt}function rf(r,e,t){return!r||!t?r===t:e.length===Object.keys(t).length&&e.every(n=>r[n]===t[n])}var la=50,rS=1e3,nS=100,sS=4,Fr=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(s,t,0).apply(e),a=this.buildParsingContext(t),c=this.parseStacktrace(o,a);return{$exception_list:this.convertToExceptionList(c,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&ge(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:n,stack:s,errors:e.errors?.map(i=>this.parseStacktrace(i,t))}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n=[],s=(i,o,a)=>{let c=n.length,l=o===void 0?{type:typeof t.type=="string"&&t.type.length>0?t.type:"generic",...typeof t.handled=="boolean"?{handled:t.handled}:t.handled===void 0?{handled:!0}:{},synthetic:typeof t.synthetic=="boolean"?t.synthetic:i.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:i.synthetic,exception_id:c,parent_id:o},u={type:i.type,value:i.value,mechanism:l};i.stack&&(u.stacktrace={type:"raw",frames:i.stack}),n.push(u),i.cause&&s(i.cause,c,"cause");for(let d of i.errors??[])s(d,c,"member")};return s(e),n}buildParsingContext(e){return{chunkIdMap:nf(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(nt(e)){let t=Object.getPrototypeOf(e);for(let n=0;t&&n<nS;n++){let s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let i=e.errors;return ge(i)?i:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,n=0){let s=0,i=0,o=!1,a=new Set,c=[],l={},u=(p,m,h=0)=>{let _=d(m,h),E=_.apply;if(_.apply=S=>{c.push(p);try{return E(S)}finally{c.pop()}},h>sS||h>0&&c.indexOf(p)!==-1)return this.coerceFallback(_);let y=typeof p=="object"&&p!==null||typeof p=="function";if(h===0&&s>=la||y&&a.has(p))return;y&&a.add(p),h===0&&s++;let w=this.getAggregateErrors(p);o||=!!w;let R;try{if(R=this.applyCoercers(p,_),!R)throw l}catch(S){if(S===l){h===0&&s--;return}if(!o)throw S;R=this.coerceFallback(_)}if(!w||s>=la)return R;let P;try{P=w.length}catch{return R}if(!Number.isInteger(P)||P<0||P>4294967295)return R;let O=[];for(let S=0;s<la&&i<rS&&S<P;S++){i++;let T;try{T=_.next(w[S])}catch{s++,T=this.coerceFallback(d(m+1))}T&&O.push(T)}return{...R,errors:O}},d=(p,m=0)=>({...t,syntheticException:p==0?t.syntheticException:void 0,mechanism:p==0?e:{},apply:h=>{let _=u(h,p,m+1);if(!_)throw l;return _},next:h=>u(h,p+1)}),g=d(n);return{...g,apply:p=>u(p,n)??this.coerceFallback(g)}}};var X="?",iS="<anonymous>",oS=/^([a-z][a-z0-9.+-]+):/i,aS=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function cS(r){if(!r||r===iS)return!1;let e=oS.exec(r);return!e||aS.includes(e[1].toLowerCase())}function Be(r,e,t,n,s){let i={platform:r,filename:e,function:t==="<anonymous>"?X:t,in_app:cS(e)};return ze(n)||(i.lineno=n),ze(s)||(i.colno=s),i}var Ws=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:X,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var lS=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,uS=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dS=/\((\S*)(?::(\d+))(?::(\d+))\)/,ua=(r,e)=>{let t=lS.exec(r);if(t){let[,s,i,o]=t;return Be(e,s,X,+i,+o)}let n=uS.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=dS.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,o]=Ws(n[1]||X,n[2]);return Be(e,o,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var fS=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pS=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,da=(r,e)=>{let t=fS.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let o=pS.exec(t[3]);o&&(t[1]=t[1]||"eval",t[3]=o[1],t[4]=o[2],t[5]="")}let s=t[3],i=t[1]||X;return[i,s]=Ws(i,s),Be(e,s,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var gS=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,sf=(r,e)=>{let t=gS.exec(r);return t?Be(e,t[2],t[1]||X,+t[3],t[4]?+t[4]:void 0):void 0};var mS=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,of=(r,e)=>{let t=mS.exec(r);return t?Be(e,t[2],t[3]||X,+t[1]):void 0},hS=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,af=(r,e)=>{let t=hS.exec(r);return t?Be(e,t[5],t[3]||t[4]||X,+t[1],+t[2]):void 0};var _S=/^\s*[-]{4,}$/,ES=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,SS=/^Promise\.(?:all|any)$/,yS=/^index \d+$/,bS="node:internal/promise",lf=(r,e)=>{let t=r.match(ES);if(t){let n,s,i,o,a;if(t[1]){i=t[1];let u=i.lastIndexOf(".");if(i[u-1]==="."&&u--,u>0){n=i.slice(0,u),s=i.slice(u+1);let d=n.indexOf(".Module");d>0&&(i=i.slice(d+1),n=n.slice(0,d))}o=void 0}s&&(o=n,a=s),s==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||X,i=o?`${o}.${a}`:a);let c=t[2]?.startsWith("file://")?t[2].slice(7):t[2],l=t[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&t[5]&&!l&&(c=t[5]),SS.test(i)&&yS.test(c||"")&&(c=bS),{filename:c?decodeURI(c):void 0,module:void 0,function:i,lineno:cf(t[3]),colno:cf(t[4]),in_app:wS(c||"",l),platform:e}}if(r.match(_S))return{filename:r,platform:e}};function wS(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function cf(r){return parseInt(r||"",10)||void 0}var uf=/\(error: (.*)\)/,df=50,TS=10,AS=1e3;function fa(r,e){return r.filename===e.filename&&r.function===e.function&&r.module===e.module&&r.lineno===e.lineno&&r.colno===e.colno}function RS(r){for(let e=1;e<=TS;e++){let t=r.length-2*e;if(t<0)break;let n=!0;for(let s=0;s<e;s++){let i=r[t+s];if(!fa(i,r[t+e+s])){n=!1;break}}if(n){for(let s=0;s<e;s++)r[t+s]=r[t+e+s];return r.length=t+e,{start:t,length:e}}}}function vS(r,e){let t=e.start+e.length,n=pf(r,e);n&&r.splice(t+n===r.length?t:e.start,n)}function ff(r,e){let t=e.start;for(;t>0&&fa(r[t-1],r[t-1+e.length]);)t--;return e.start-t}function pf(r,e){let t=e.start+e.length,n=t;for(;n<r.length&&fa(r[n],r[n-e.length]);)n++;return n-t}function MS(r,e){let t=e[0],n=r.length-(t?ff(r,t):0);for(let s of e)n-=pf(r,s);return n}function OS(r){let e=r.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),t=0;for(let n=1;n<e.length;n++)CS(e,n,t)&&(t=n);r.push(...r.splice(0,t))}function CS(r,e,t){for(let n=0;n<r.length;n++){let s=r[(e+n)%r.length],i=r[(t+n)%r.length];if(s!==i)return s<i}return!1}function gf(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,df).map(t=>({...t,filename:t.filename||IS(e).filename,function:t.function||X}))}function IS(r){return r[r.length-1]||{}}function pa(){return mf("web:javascript",ua,da)}function mf(r,...e){return(t,n=0)=>{let s=[],i=t.split(`
31
31
  `),o=Math.min(i.length,n+AS),a=[];for(let u=n;u<o;u++){let d=i[u];if(d.length>1024)continue;let g=uf.test(d)?d.replace(uf,"$1"):d;if(!g.match(/\S*Error: /)){for(let p of e){let m=p(g,r);if(m){s.push(m);let h=RS(s);if(h){for(let _=a.length-1;_>=0;_--){let E=a[_];if(E.start+E.length<=h.start)break;a.pop()}a.push(h)}break}}if(MS(s,a)>=df)break}}let c=[...a].sort((u,d)=>d.start-u.start),l=c[c.length-1];if(l){let u=ff(s,l);s.splice(l.start-u,u);for(let d of c)d.start-=u}for(let u of c)vS(s,u);return a.some(u=>u.start===0&&s.length===u.length)&&OS(s),gf(s)}}var ga=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let n=ee(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return yt(e,"DOMException")}isDOMError(e){return yt(e,"DOMError")}};var Ur=class{match(e){return nt(e)}coerce(e,t){let n=this.getStack(e),s=n===void 0?t.syntheticException?.stack:void 0,i=!!s;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??s,cause:e.cause?t.next(e.cause):void 0,synthetic:i}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){try{let t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;let n=e.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}};var ma=class{match(e){if(!Od(e))return!1;let t=e;return t.error!=null||this._hasUsableMessage(t)}coerce(e,t){if(e.error!=null)return t.apply(e.error);let n=t.apply(e.message);return{...n,stack:this._buildLocationStack(e)??n.stack,synthetic:!0}}_hasUsableMessage(e){return ee(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e,n=t.lineno??0,s=t.colno??0;if(!(!ee(t.filename)||t.filename.length===0)&&n!==0)return`Error
32
- at ${t.filename}:${n}:${s}`}};var PS=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,$r=class{match(e){return typeof e=="string"}coerce(e,t){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,s=e.match(PS);return s&&(t=s[1],n=s[2]),[t,n]}};var hf=["fatal","error","warning","log","info","debug"];function Hs(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let s=t.slice(0,n).join(", ");if(!(s.length>e))return n===t.length||s.length<=e?s:`${s.slice(0,e)}...`}return""}var Br=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(zt(e))return e.constructor.name;let t="name"in e?e.name:void 0;return ee(t)&&!Xo(t)?t:"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 t=this.getObjectClassName(e),n=Hs(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return ee(e)&&!Xo(e)&&hf.indexOf(e)>=0}getStack(e){try{return ee(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ee(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(nt(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var ha=class{match(e){return zt(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Hs(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Wr=class{match(e){return Cs(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var _a=class{match(e){return yt(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!zt(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return Cs(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.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 Ea=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var Hr={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kS=new Set([Hr.MESSAGE,Hr.TIMESTAMP]),js={enabled:!0,max_bytes:32768};function Sa(r){return r?{enabled:r.enabled??js.enabled,max_bytes:DS(r.max_bytes,js.max_bytes)}:{...js}}function xS(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,s)=>kS.has(s)?(e.push(s),n):(n[s]=r[s],n),{}),droppedKeys:e}}var ya=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Sa(e)}setConfig(e){this._config=Sa(e),this._trimToMaxBytes()}add(e){let t=LS(e);if(!t)return;let n=_f(t.json);n>this._config.max_bytes||(this._entries.push({step:t.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 DS(r,e){if(!Gt(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function LS(r){let e;try{e=rt(r)}catch{return}try{let t=JSON.parse(e);if(!xr(t))return;let n=t,s=n[Hr.MESSAGE],i=n[Hr.TIMESTAMP];return!ee(s)||s.trim().length===0||!ee(i)&&!Gt(i)?void 0:{step:n,json:e}}catch{return}}function _f(r){if("u">typeof TextEncoder)return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}function NS(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let r=globalThis._posthogReleaseId;return typeof r=="string"&&r.length>0?r:void 0}var ba=r=>{if("flags"in r){let e=Ef(r.flags),t=Sf(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([s,i])=>[s,Xt(i)])),n=Object.fromEntries(Object.entries(e).map(([s,i])=>[s,FS(s,i,t[s])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function FS(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var Ef=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,jr(t)]).filter(([,e])=>e!==void 0)),Sf=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?Xt(n):void 0]}))},jr=r=>r===void 0?void 0:r.variant??r.enabled,Xt=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var yf=["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"],US=["$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",...yf,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Kr=(r,e=[])=>{let t={},n=s=>{r[s]!==void 0&&(t[s]=r[s])};return US.forEach(n),e.forEach(n),t};var Ks=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};function wa(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var BS="NativeGzipValidationError",WS=31,HS=139,jS=8,KS=r=>r.length>=2&&r[0]===WS&&r[1]===HS;var Gr,GS=()=>{if(Gr)return Gr;Gr=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;Gr[r]=e>>>0}return Gr},zS=r=>{let e=GS(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},Gs=r=>{throw Yt(BS,`Native gzip produced invalid output: ${r}`)},VS=async(r,e)=>{r.size<18&&Gs("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!KS(t)||t[2]!==jS)&&Gs("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==zS(e)&&Gs("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&Gs("invalid-size")};async function zr(r,e=!0,t){try{let n=new TextEncoder().encode(r),s=new globalThis.CompressionStream("gzip"),i=s.writable.getWriter(),o=i.write(n).then(()=>i.close()).catch(async l=>{try{await i.abort(l)}catch{}throw l}),a=new Response(s.readable).blob(),[c]=await Promise.all([a,o]);return await VS(c,n),c}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var ye=class extends Error{constructor(e,t,n,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=n,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return oa(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=Yt("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=ce(()=>{this._bodyReadTimedOut=!0;let i=Yt("AbortError","Response body read timed out");s(i),this.cancelResponseBody(i)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(n){t=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([t,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{}})()}},qe=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var qS=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function bf(r){if(r instanceof ye){let e="";try{e=await r.text}catch{r.bodyReadTimedOut&&(e="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function YS(r){return typeof r=="object"&&(r instanceof ye||Rf(r))}function Rf(r){return r instanceof qe}function JS(r){if(r instanceof ye)return r.status===502||r.status===504;if(!(r instanceof qe))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var wf=10485760;function Tf(r){try{return typeof r!="string"?r instanceof Uint8Array?r.byteLength:r.size:"u">typeof Buffer?Buffer.byteLength(r,Jd):new TextEncoder().encode(r).length}catch{return 0}}function Qt(r){return typeof r=="object"&&r instanceof ye&&r.status===413}function zs(r){return r instanceof ye?r.status===408||r.status===429||r.status>=500:Rf(r)}function Af(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ta="default",Vr=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Fr([new Ur,new Br,new $r,new Wr],pa())}getEvaluationRuntime(){}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ds,this._events=new Ks,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof t.host=="string"?t.host.trim():"",i=!n;this._logger=Ld("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Xd(s||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:zs},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!wa()||(t?.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(de.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(de.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(de.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,s)=>this._logger.info(n,s));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n=this.mergeCommonEventProperties(t);return qS(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Kr(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,t,n){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",s,n)})}async identifyStatelessImmediate(e,t,n){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",s,n)}captureStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",i,s)})}async captureStatelessImmediate(e,t,n,s){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",i,s)}aliasStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",i,s)})}async aliasStatelessImmediate(e,t,n,s){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,s)}groupIdentifyStateless(e,t,n,s,i,o){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});this.enqueue("capture",a,s)})}async groupIdentifyStatelessImmediate(e,t,n,s,i,o){let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});await this.sendImmediate("capture",a,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,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,t={},n={},s={},i={},o=!1){await this._initPromise;let a=o?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:s,...i};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,d,{type:"required",consume:g=>g.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:JS},this.featureFlagsRequestTimeoutMs).then(g=>({success:!0,response:ba(g)})).catch(g=>(this._events.emit("error",g),{success:!1,error:this.categorizeRequestError(g)}))}categorizeRequestError(e){if(e instanceof ye)return{type:"api_error",statusCode:e.status};if(e instanceof qe){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,s,i,o);if(a===void 0)return{response:void 0,requestId:void 0};let c=jr(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,s,i,o,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,s,i,o,[e]);if(!a)return;let c=a[e];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(e,t={},n={},s={},i,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)).payloads}async getFeatureFlagsStateless(e,t={},n={},s={},i,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,s,i,o);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};o&&(a.flag_keys_to_evaluate=o);let c=await this.getFlags(e,t,n,s,a);if(!c.success)return;let l=c.response;return l.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"),l.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:l?.requestId,quotaLimited:l.quotaLimited}):l}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}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,t,{type:"required",consume:i=>{if(i.status!==200||!i.json){let o=`Surveys API could not be loaded: ${i.status}`,a=new Error(o);return this._logger.error(a),this._events.emit("error",new Error(o)),Promise.resolve(void 0)}return i.json()}}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return s&&this._logger.info("Surveys fetched from API: ",JSON.stringify(s)),s??[]}get props(){return this._props||(this._props=this.getPersistedProperty(de.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(de.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(de.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Ta}persistedQueueKeyForRoute(e){return de.Queue}getActiveQueueRoutes(){return[Ta]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let o=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(i)),a=this.getPersistedProperty(o)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:i}),this.setPersistedProperty(o,a),this._events.emit(e,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=ce(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i!==null){i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,s??this.getQueueRouteKey(i))}catch(o){this._events.emit("error",o)}}}normalizeMessage(e){let{type:t,library:n,library_version:s,...i}=e,o=Af(i.properties)?i.properties:void 0;return n!==void 0&&o?.$lib===void 0&&(o={...o||{},$lib:n}),s!==void 0&&o?.$lib_version===void 0&&(o={...o||{},$lib_version:s}),o&&(i.properties=o),i.uuid=wt(i.uuid,ae),i}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let n=t.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,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:aa(),uuid:wt(t?.uuid,ae)};return(t?.disableGeoip??this.disableGeoip)&&(Af(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 bf(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let n=t.filter(i=>!!i),s=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;s>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(o=>o.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,s])}).then(()=>Nr([t])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Nr([s]).then(()=>{this.flushPromises.delete(s),this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this.flushPromise===s&&(this.flushPromise=null)}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}compressPayload(e){return zr(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,n=Ta){let s={api_key:this.apiKey,batch:e.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:aa()};this.historicalMigration&&(s.historical_migration=!0);let i=rt(s),o=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(i),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await this.fetchWithRetry(o,c,{type:"successful-write"},t)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(s=>this.getRouteQueue(s).length>0))return;let t=[],n;for(let s of e)try{await this._flushRoute(s,t)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(n)||[];if(!s.length)return;let i=s.length,o=0;for(;s.length>0&&o<i;){let a=s.slice(0,this.maxBatchSize),c=a.map(d=>d.message===void 0?d.message:this.normalizeMessage(d.message)),l=async()=>{let d=this.getPersistedProperty(n)||[],g=[...a],p=d.filter(m=>{let h=m.message?.uuid,_=g.findIndex(E=>E===m||typeof h=="string"&&h.length>0&&E.message?.uuid===h);return _===-1?!0:(g.splice(_,1),!1)});this.setPersistedProperty(n,p),s=p,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:d=>Qt(d)?!1:zs(d)};try{await this.sendBatch(c,u,e)}catch(d){if(Qt(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 qe||await l(),this._events.emit("error",d),d}await l(),t.push(...c),o+=c.length}}async _sendOtlpBatch({path:e,auth:t,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let s;try{s=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let i=Tf(s);if(i>wf)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${i} bytes: the endpoint accepts at most ${wf}`)),{kind:"too-large",measuredLocally:!0};let o=t==="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,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(o,l,{type:"successful-write"},{retryCheck:u=>Qt(u)||u instanceof ye&&u.retryAfterMs!==void 0?!1:zs(u)}),{kind:"ok"}}catch(u){if(Qt(u))return{kind:"too-large"};if(zs(u)){let d=u instanceof ye?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...d!==void 0&&{retryAfterMs:d}}}return{kind:"fatal",error:u}}}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,t,n,s,i){let o=t.body?t.body:"",a=Tf(o),c={...this._retryOptions,...s},l=0;return await Qd(async()=>{l++;let u=new AbortController,d=i??this.requestTimeout,g=Date.now()+d,p,m=new Promise((w,R)=>{p=ce(()=>{let P=Yt("AbortError",`Request timed out after ${d}ms`);R(P),u.abort(P)},d)}),h,_=!1,E,y=()=>E??=(async()=>{try{await h?.body?.cancel()}catch{}})();try{let w;try{w=this.fetch(e,{signal:u.signal,...t})}catch(O){throw new qe(O)}w.then(O=>{u.signal.aborted&&!_&&Promise.resolve(O.body?.cancel()).catch(()=>{})}).catch(()=>{});try{h=await Promise.race([w,m]),_=!0}catch(O){throw new qe(O)}let R=t.mode==="no-cors",P=n.type==="successful-write"?300:400;if(!R&&(h.status<200||h.status>=P))throw new ye(h,a,g,u);if(n.type==="successful-write"){try{await Promise.race([y(),m])}catch{}return}try{return await Promise.race([n.consume(h),m])}catch(O){throw u.signal.aborted?new qe(O):O}}finally{clearTimeout(p),u.signal.aborted&&h&&y()}},{...c,retryCheck:u=>{let d=c.retryCheck(u);return d&&l<=c.retryCount&&u instanceof ye&&u.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;return this.clearFlushTimer(),this.disabled?void 0:st((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(o=>this.getRouteQueue(o).length>0);){let i=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===i){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!YS(s))throw s;await bf(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!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 ty=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var nP=new RegExp(ty.source,"i"),vf=/[a-z][a-z0-9+.-]{0,63}:\/\//i,sP=new RegExp(`^${vf.source}`,"i"),iP=new RegExp(vf.source,"gi");var ry=["is_not","is_set"],ny=1152921504606847e3,v=class r extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,r.prototype)}};function Aa(r){if(typeof r=="boolean")return!0;if(typeof r=="string"){let e=r.toLowerCase();return e==="true"||e==="false"}if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!Aa(e in r?r[e]:null))return!1;return!0}function Ra(r){if(typeof r=="boolean")return r;if(typeof r=="string")return r.toLowerCase()==="true";if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!Ra(e in r?r[e]:null))return!1;return!0}function qr(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t>=55296&&t<=56319){let n=r.charCodeAt(e+1);if(e+1>=r.length||n<56320||n>57343)throw new v("Cannot stringify an unpaired surrogate like the flags service");e++}else if(t>=56320&&t<=57343)throw new v("Cannot stringify an unpaired surrogate like the flags service")}}function qs(r,e=new Set){if(!(r===null||typeof r=="boolean")){if(typeof r=="string")return void qr(r);if(typeof r=="number"){if(!Number.isFinite(r))throw new v(`Cannot represent non-finite number ${r} like the flags service`);return}if(Array.isArray(r)){if(e.has(r))throw new v("Cannot represent a circular array during local evaluation");e.add(r);try{for(let t=0;t<r.length;t++)t in r&&qs(r[t],e)}finally{e.delete(r)}return}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new v("Cannot represent a non-JSON object like the flags service");if(e.has(r))throw new v("Cannot represent a circular object during local evaluation");e.add(r);try{for(let n of Object.keys(r))qr(n),qs(r[n],e)}finally{e.delete(r)}return}throw new v(`Cannot represent ${typeof r} like the flags service`)}}function sy(r,e){let t=0,n=0;for(;t<r.length&&n<e.length;){let s=r.charCodeAt(t),i=e.charCodeAt(n),o=s>=55296&&s<=56319,a=i>=55296&&i<=56319,c=o?r.charCodeAt(t+1):0,l=a?e.charCodeAt(n+1):0,u=o?(s-55296)*1024+c-56320+65536:s,d=a?(i-55296)*1024+l-56320+65536:i;if(u!==d)return u-d;t+=o?2:1,n+=a?2:1}return r.length-e.length}function va(r,e=new Set){if(r===null)return"null";if(typeof r=="string")return qr(r),JSON.stringify(r);if(typeof r=="boolean")return r?"true":"false";if(typeof r=="number"){if(!Number.isFinite(r))throw new v(`Cannot stringify non-finite number ${r} like the flags service`);if(Number.isInteger(r))throw new v(`Cannot distinguish integer ${r} from an integral JSON float during local evaluation`);return String(r)}if(Array.isArray(r)){if(e.has(r))throw new v("Cannot stringify a circular array during local evaluation");e.add(r);try{let t=[];for(let n=0;n<r.length;n++)t.push(n in r?va(r[n],e):"null");return`[${t.join(",")}]`}finally{e.delete(r)}}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new v("Cannot stringify a non-JSON object like the flags service");if(e.has(r))throw new v("Cannot stringify a circular object during local evaluation");e.add(r);try{let n=Object.keys(r);return n.forEach(qr),`{${n.sort(sy).map(s=>`${JSON.stringify(s)}:${va(r[s],e)}`).join(",")}}`}finally{e.delete(r)}}throw new v(`Cannot stringify ${typeof r} like the flags service`)}function Vs(r){return typeof r=="string"?(qr(r),r):va(r)}function Mf(r){try{return new RegExp(r),!0}catch{return!1}}function be(r){return String(r).replace(/[A-Z]/g,e=>e.toLowerCase())}function Cf(r,e,t){if(!/^\d+$/.test(r)||t==="strict"&&r.length>1&&r[0]==="0")throw new v(`Invalid semver: ${e}`);return parseInt(r,10)}function G(r,e="strict"){let n=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new v(`Invalid semver: ${r}`);let s=n.split("."),i=o=>o===void 0||o===""?0:Cf(o,r,e);return[i(s[0]),i(s[1]),i(s[2])]}function we(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function iy(r,e){let t=G(r,e);return{lower:[t[0],t[1],t[2]],upper:[t[0],t[1]+1,0]}}function oy(r,e){let[t,n,s]=G(r,e),i=[t,n,s],o;return o=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,s+1],{lower:i,upper:o}}function ay(r,e){let n=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new v(`Invalid wildcard semver: ${r}`);let s=n.split("."),i=c=>{if(e==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return Cf(c,r,e)}catch{}throw new v(`Invalid wildcard semver: ${r}`)},o=i(s[0]);if(s.length===1)return{lower:[o,0,0],upper:[o+1,0,0]};let a=i(s[1]);return{lower:[o,a,0],upper:[o,a+1,0]}}function Of(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new v(`${r} is in an invalid date format`)}throw new v(`The date provided ${r} must be a string, number, or date object`)}function Ma(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t||!t.groups)return null;let s=parseInt(t.groups.number);if(s>=1e4)return null;let i=t.groups.interval;if(i==="h")n.setUTCHours(n.getUTCHours()-s);else if(i==="d")n.setUTCDate(n.getUTCDate()-s);else if(i==="w")n.setUTCDate(n.getUTCDate()-7*s);else if(i==="m")n.setUTCMonth(n.getUTCMonth()-s);else{if(i!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-s)}return n}function Oa(r,e,t={}){let n=r.key,s=r.value,i=r.operator||"exact",o=t.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(e,n)){if(i==="is_not_set")return!1;if(i==="is_set")return!0}else throw new v(`Property ${n} not found in propertyValues`);let c=e[n];if(c===void 0)return t.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${i} operator`),i==="is_not";if(c===null&&!ry.includes(i)&&i!=="exact"&&i!=="is_not")return t.warnFunction?.(`Property ${n} cannot have a value of null with the ${i} operator`),!1;let l=(d,g)=>{if(t.propertyMatchingVersion!==2&&Aa(d)||Array.isArray(d)&&d.length===0)return qs(g),Ra(d)===Ra(g);if(t.propertyMatchingVersion===2&&typeof g=="number"&&Aa(d))return qs(g),!1;if(Array.isArray(d)){let p=Vs(g).toLowerCase();return d.some(m=>Vs(m).toLowerCase()===p)}return Vs(d).toLowerCase()===Vs(g).toLowerCase()},u=(d,g,p)=>{if(p==="gt")return d>g;if(p==="gte")return d>=g;if(p==="lt")return d<g;if(p==="lte")return d<=g;throw new Error(`Invalid operator: ${p}`)};switch(i){case"exact":return l(s,c);case"is_not":return!l(s,c);case"is_set":return!0;case"icontains":return be(c).includes(be(s));case"not_icontains":return!be(c).includes(be(s));case"starts_with":return be(c).startsWith(be(s));case"not_starts_with":return!be(c).startsWith(be(s));case"ends_with":return be(c).endsWith(be(s));case"not_ends_with":return!be(c).endsWith(be(s));case"regex":return Mf(String(s))&&String(c).match(String(s))!==null;case"not_regex":return Mf(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)),g=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(d)&&Number.isFinite(g)?u(g,d,i):u(String(c),String(s),i)}case"is_date_after":case"is_date_before":{if(typeof s=="boolean")throw new v("Date operations cannot be performed on boolean values");let d=Ma(String(s));d==null&&(d=Of(s));let g=Of(c);return i==="is_date_before"?g<d:g>d}case"semver_eq":return we(G(String(c),o),G(String(s),o))===0;case"semver_neq":return we(G(String(c),o),G(String(s),o))!==0;case"semver_gt":return we(G(String(c),o),G(String(s),o))>0;case"semver_gte":return we(G(String(c),o),G(String(s),o))>=0;case"semver_lt":return we(G(String(c),o),G(String(s),o))<0;case"semver_lte":return we(G(String(c),o),G(String(s),o))<=0;case"semver_tilde":{let d=G(String(c),o),{lower:g,upper:p}=iy(String(s),o);return we(d,g)>=0&&we(d,p)<0}case"semver_caret":{let d=G(String(c),o),{lower:g,upper:p}=oy(String(s),o);return we(d,g)>=0&&we(d,p)<0}case"semver_wildcard":{let d=G(String(c),o),{lower:g,upper:p}=ay(String(s),o);return we(d,g)>=0&&we(d,p)<0}default:throw new v(`Unknown operator: ${i}`)}}async function If(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function Yr(r,e,t="",n="."){let s=await If(`${r}${n}${e}${t}`);return parseInt(s.slice(0,15),16)/ny}async function Ca(r,e){if(r==null||r.id==null||r.exclusion_percentage==null)return;let t=Number(r.exclusion_percentage);if(!Number.isFinite(t))return;let n=Math.min(Math.max(t,0),100);if(!(n!==100&&await Yr("holdout",e,"","-")>n/100))return`holdout-${r.id}`}function Ys(r){let e=[],t=0;for(let n of r){let s=t+n.rollout_percentage/100;e.push({valueMin:t,valueMax:s,key:n.key}),t=s}return e}async function Ia(r,e,t){let n=await Yr(r,e,"variant");return Ys(t).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function Pa(r,e){if(e===!1||e==null||!r)return null;let t=typeof e=="boolean"?e.toString():e,n=r[t]||null;return n==null?null:Xt(n)}var Pf=9223372036854776e3,cy="9223372036854775808",ly=Object.prototype.propertyIsEnumerable;function uy(){return{ancestors:new WeakSet,remainingNodes:1e4}}function We(r,e){try{return kf(r,e,uy(),0)}catch{return[]}}function dy(r,e){let t=r.toString(),n=BigInt(cy);return r>=n||r<-n?(e?.debug(`Attribute ${t} is outside the int64 range; encoding it as a string`),{stringValue:t}):{intValue:t}}function Da(r,e,t,n){if(t.remainingNodes<=0)return{stringValue:Bs};if(t.remainingNodes--,Md(r))return{boolValue:r};if(typeof r=="bigint")return dy(r,e);if(typeof r=="number"){if(!Number.isFinite(r))return{stringValue:String(r)};if(Number.isInteger(r)){if(Number.isSafeInteger(r))return{intValue:String(r)};if("u"<typeof BigInt)return{stringValue:String(r)};let s=BigInt(r).toString();return r>=Pf||r<-Pf?(e?.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}}return{doubleValue:r}}if(typeof r=="string")return{stringValue:$e(r)};if(typeof r=="function")return{stringValue:Yd};if(typeof r=="symbol")return{stringValue:String(r)};if(typeof r=="object"&&r!==null){if(t.ancestors.has(r))return{stringValue:$s};if(n>=20)return{stringValue:Bs};if(r instanceof Date){let s=r.getTime(),i=Number.isFinite(s)?r.toISOString():String(r);return{stringValue:typeof i=="string"?$e(i):String(i)}}t.ancestors.add(r);try{try{let s=r.toJSON;if(typeof s=="function")return Da(s.call(r),e,t,n+1)}catch{}return ge(r)?{arrayValue:{values:fy(r,e,t,n+1)}}:{kvlistValue:{values:kf(r,e,t,n+1)}}}finally{t.ancestors.delete(r)}}return{stringValue:$e(String(r))}}function fy(r,e,t,n){let s=[],i=Math.min(r.length,1e3),o=0;for(;o<i&&t.remainingNodes>0;o++)try{let a=o in r?r[o]:void 0;if(Oe(a))continue;s.push(Da(a,e,t,n))}catch{s.push({stringValue:Se})}return r.length>o&&s.push({stringValue:Bs}),s}function kf(r,e,t,n){let s=[];for(let i in r)if(ly.call(r,i)){if(!i){e?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||t.remainingNodes<=0){e?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let o=r[i];if(Qo(o)||ze(o))continue;s.push({key:$e(i),value:Da(o,e,t,n)})}catch{s.push({key:$e(i),value:{stringValue:Se}})}}return s}function Xr(r,e,t){return{...Ve({},r.resourceAttributes),"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}var py=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function Qr(r,e){let t=Ve({},r),n={};for(let s of py)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s],delete t[s]);return[...We(t,e),...We(n,e)]}var xf={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 gy(r){if(r)return Object.prototype.hasOwnProperty.call(xf,r)?xf[r]:r}function La(r,e){let t=gy(r);return{...t?{"os.name":t}:{},...e?{"os.version":e}:{}}}var my={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}},bP=my.info;var Tt=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=ce(()=>{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 Zr(){return 1-.25+Math.random()*.25*2}var Te=1;function en(r,e,t,n){let s=Math.min(Math.max(0,e-1),6),i=r*2**s,o=n===void 0?i:Math.min(i,Math.max(n,r));return Math.round(o*t)}var Na="0000000000000000",Sy=Na+Na,yy=/^[0-9a-f]+$/;function by(r){let e=new Uint8Array(r),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")try{return t.getRandomValues(e),e}catch{}for(let n=0;n<r;n++)e[n]=Math.floor(256*Math.random());return e}function wy(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function Df(r){let e=wy(by(r));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Lf(){return Df(16)}function Nf(){return Df(8)}function Ff(r,e,t){return typeof r=="string"&&r.length===e&&r!==t&&yy.test(r)}function Uf(r){return Ff(r,32,Sy)}function $f(r){return Ff(r,16,Na)}var Ty=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Xs(r){let e=Bf(r);return e&&{traceId:e.traceId,spanId:e.spanId,flags:Ay(e.flags)}}function Ay(r){return 1&parseInt(r,16)?Zt:Ry}function Bf(r){if(typeof r!="string")return;let e=Ty.exec(r.trim());if(!e)return;let[,t,n,s,i,o]=e;if(t!=="ff"&&!(t==="00"&&o)&&!(!Uf(n)||!$f(s)))return{version:t,traceId:n,spanId:s,flags:i}}function Wf(r){return Bf(r)&&r.trim()}function Qs(r){return Array.isArray(r)&&r.length===1?r[0]:r}var Zt="01",Ry="00";function Hf(r,e,t=Zt){return`00-${r}-${e}-${t}`}var vy=32,Fa=512;function Zs(r){if(typeof r!="string")return;let e=r.trim();if(!e||/[^\x20-\x7e\t]/.test(e))return;let t=e.split(",");if(!(t.length>vy)){for(let n of t)if(n.trim()&&!n.includes("="))return;return e.length<=Fa?e:Oy(t)}}var My=128;function Oy(r){let e=[...r],t=()=>e.reduce((n,s)=>n+s.length,0)+e.length-1;for(let n=e.length-1;n>=0&&t()>Fa;n--)e[n].length>My&&e.splice(n,1);for(;e.length&&t()>Fa;)e.pop();return e.length?e.join(","):void 0}var tn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ei(r){return String(r)+"000000"}function Ua(r,e,t,n){let s="";return n&&(s=Object.keys(n).sort().map(o=>`${JSON.stringify(o)}:${JSON.stringify(n[o])}`).join(",")),`${r}\0${e}\0${t??""}\0${s}`}function jf(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function $a(r,e,t){return Xr(r,e,t)}function Ba(r,e,t,n){return{resourceMetrics:[{resource:{attributes:Qr(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function ti(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var Kf=1,rn=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushTimer=new Tt(()=>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 bt,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,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=Te,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 t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,s;try{n=t.attributes?{...t.attributes}:void 0,s=Ua(t.type,t.name,t.unit,n)}catch(c){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,c);return}let i=this._series.get(s);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(s,i)}let o=this._typeByName.get(t.name);o===void 0?this._typeByName.set(t.name,t.type):o!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,t.value);let a=this._activeTraceContext();a&&(i.exemplar={...a,value:t.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=Xs(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Zt)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,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(tn.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[jf(t,tn)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=ge(t)?t:[t],s=e;for(let i of n)try{let o=i(s);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;s=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(en(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 t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=Zr()):(this._consecutiveFlushFailures=0,this._flushJitter=Te),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 Ba(this._buildMetrics(e),$a(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=ei(Date.now()),n=new Map;for(let s of e.values()){let i=Ua(s.type,s.name,s.unit,void 0),o=n.get(i);o||(o={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count"?o.sum={aggregationTemporality:Kf,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:Kf,dataPoints:[]},n.set(i,o));let a=We(s.attributes??{},this._logger),c=ei(s.windowStartMs),l=Cy(s.exemplar);if(s.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:t,asDouble:s.total??0,...l};o.sum.dataPoints.push(u)}else if(s.type==="gauge"){let u={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};o.gauge.dataPoints.push(u)}else if(s.hist){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:tn,...l};o.histogram.dataPoints.push(u)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let s=this._series.get(t);if(!s){this._admitNewSeries()&&this._series.set(t,n);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,n.windowStartMs),s.exemplar=s.exemplar??n.exemplar,s.type){case"count":s.total=(s.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(s.hist){s.hist.count+=n.hist.count,s.hist.sum+=n.hist.sum,s.hist.min=Math.min(s.hist.min,n.hist.min),s.hist.max=Math.max(s.hist.max,n.hist.max);for(let i=0;i<s.hist.bucketCounts.length;i++)s.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else s.hist=n.hist;break}}}};function Cy(r){return r?{exemplars:[{filteredAttributes:[],timeUnixNano:ei(r.timeMs),asDouble:r.value,traceId:r.traceId,spanId:r.spanId}]}:{}}var Gf="unknown";function At(r,e,t,n){return typeof r=="string"&&r.trim()?r.length>t?r.slice(0,t):r:(n?.debug(`${e} must be a non-empty string; using "${Gf}"`),Gf)}function er(r){if(r==null)return;let e=r;if(r instanceof Date)try{e=r.getTime()}catch{return}if(!(typeof e!="number"||!Number.isFinite(e))&&!(e<0||e>9223372036854))return e}function zf(r,e,t){let n=er(r);return n===void 0?(r!==void 0&&t?.debug("Span startTime is out of range or not a valid time; using the current time"),e):(e-n>864e5?t?.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&&t?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function ri(r,e){return r<e?e:r}function nn(r,e,t,n){let s=er(r);return s===void 0?(r!==void 0&&n?.debug(`Span ${t} is out of range or not a valid time; using the derived time`),e):s}function si(){let r=globalThis.performance;return typeof r?.now=="function"?r.now():void 0}var tr=class{constructor(e,t,n){this._onEnd=t,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??Zt,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:si(),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=si();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,t){if(Oe(t)){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]=oi(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=Ve({},e);for(let n of Object.keys(t))this._writeAttribute(n,t[n])}return this}addEvent(e,t,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=t&&Jf(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:At(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:nn(n,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,t){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,...t&&{message:Wa(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:n,stack:s}=Ha(e);return this.addEvent(Iy,{"exception.type":t,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=At(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Hf(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 t=this._now(),n=nn(e,t,"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:ri(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Iy="exception",Py=4294967295;function ky(r){try{return typeof r=="string"?r:String(r)}catch{return Se}}function Rt(r){return typeof r!="number"||!Number.isFinite(r)||r<=0?0:Math.min(Math.floor(r),Py)}function xy(r,e){if(!e.length)return Object.keys(r);let t=e.filter(s=>Object.prototype.propertyIsEnumerable.call(r,s)),n=new Set(t);return[...t,...Object.keys(r).filter(s=>!n.has(s))]}function qf(r,e,t,n,s,i,o=[]){let a=0,c=0,l={};for(let p of xy(r.attributes,o)){let m=r.attributes[p];if(!Oe(m)){if(!e.has(p)){if(a>=t){c++;continue}a++}Object.defineProperty(l,p,{value:oi(m,i),enumerable:!0,writable:!0,configurable:!0})}}r.attributes=l,c&&(r.droppedAttributesCount=Rt(r.droppedAttributesCount)+c);let u=0,d=0,g=[];for(let p of r.events){if(u>=n){d++;continue}if(u++,p.attributes){let m=Jf(p.attributes,s,i);p.attributes=m.attributes,m.dropped&&(p.droppedAttributesCount=Rt(p.droppedAttributesCount)+m.dropped)}g.push(p)}r.events=g,d&&(r.droppedEventsCount=Rt(r.droppedEventsCount)+d),r.status?.message&&(r.status={...r.status,message:Wa(ky(r.status.message),i)})}var ii=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(){}},Yf=new ii,sn=class extends ii{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Dy(r){try{let e=r.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function it(r,e){let t=Qs(r?.parent)??e,n=typeof t=="string"||t==null?t:Vf(t,"traceparent"),s=Wf(n);if(!s)return Yf;let i=typeof t=="string"||t==null?r?.tracestate:Vf(t,"tracestate");return new sn(s,Zs(i))}function Vf(r,e){try{let t=r[e];return typeof t=="function"?t.call(r):void 0}catch{return}}function Wa(r,e){return r.length>e?r.slice(0,e):r}function oi(r,e){return ni(r,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function ni(r,e,t,n){if(r===null||typeof r!="object")return Oe(r)||t.remainingNodes<=0?r:(t.remainingNodes--,typeof r=="string"?Wa(r,e):r);if(t.ancestors.has(r))return $s;if(t.remainingNodes<=0||n>=20)return r;t.remainingNodes--,t.ancestors.add(r);try{if(r instanceof Date)return r;let s=Ly(r);if(s.selfDescribed)return Oe(s.value)?String(s.value):ni(s.value,e,t,n+1);if(ge(r)){let a=Math.min(r.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(ni(r[l],e,t,n+1))}catch{c.push(Se)}return r.length>a&&(c.length=r.length),c}let i={},o=0;for(let a of Object.keys(r)){if(o>=1e3)break;let c;try{c=ni(r[a],e,t,n+1)}catch{c=Se}a&&!Oe(c)&&o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return i}catch{return r}finally{t.ancestors.delete(r)}}function Ly(r){try{let e=r.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(r)}}catch{}return{selfDescribed:!1}}function Jf(r,e,t){let n;try{n=Object.keys(r)}catch{return{attributes:{},dropped:0}}let s={},i=0,o=0;for(let a of n){if(i>=e){o++;continue}let c;try{c=oi(r[a],t)}catch{c=Se}Oe(c)||(i++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:o}}function Xf(r,e){for(let t of Object.keys(r))r[t]=oi(r[t],e);return r}function on(r,e,t){return e===Yf?t(e):r.with(e,()=>t(e))}function Ha(r){try{let e=Dy(r);if(nt(r))return{type:r.name||"Error",message:r.message||"",...e};if(typeof r=="string")return{type:"string",message:r};if(r&&typeof r=="object"){let t=r;if(typeof t.message=="string")return{type:typeof t.name=="string"?t.name:"Object",message:t.message,...e}}return{type:typeof r,message:String(r)}}catch{return{type:typeof r,message:""}}}var ja={internal:1,server:2,client:3,producer:4,consumer:5},Ny={ok:1,error:2},Fy=1,Uy=256,$y=512;function By(r){let e=parseInt(r.traceFlags,16);return(Number.isFinite(e)?255&e:Fy)|Uy|(r.parentIsRemote?$y:0)}function ai(r){if(typeof r=="string")return $e(r);try{return $e(String(r))}catch{return Se}}function Wy(r){return r&&Object.prototype.hasOwnProperty.call(ja,r)?ja[r]:ja.internal}function Ka(r){let e=Math.floor(r),t=Math.round((r-e)*1e6);return t>=1e6&&(e+=1,t=0),String(e)+String(t).padStart(6,"0")}function Hy(r,e){let t={name:ai(r.name),timeUnixNano:Ka(r.timestamp)};if(r.attributes){let s=We(r.attributes,e);s.length&&(t.attributes=s)}let n=Rt(r.droppedAttributesCount);return n&&(t.droppedAttributesCount=n),t}function Qf(r,e){let t={traceId:r.traceId,spanId:r.spanId,name:ai(r.name),kind:Wy(r.kind),startTimeUnixNano:Ka(r.startTime),endTimeUnixNano:Ka(r.endTime),flags:By(r)};r.parentSpanId&&(t.parentSpanId=r.parentSpanId),r.traceState&&(t.traceState=ai(r.traceState));let n=We(r.attributes,e);n.length&&(t.attributes=n),r.events.length&&(t.events=r.events.map(o=>Hy(o,e)));let s=Rt(r.droppedAttributesCount);s&&(t.droppedAttributesCount=s);let i=Rt(r.droppedEventsCount);return i&&(t.droppedEventsCount=i),r.status&&(t.status={code:Ny[r.status.code],...r.status.message&&{message:ai(r.status.message)}}),t}function Zf(r,e,t){return Xr(r,e,t)}function ep(r,e,t,n,s){return{resourceSpans:[{resource:{attributes:Qr(e,s)},scopeSpans:[{scope:{name:t,version:n},spans:r}]}]}}var tp=8;function ci(){return si()??Date.now()}function Ga(r){try{return r instanceof tr}catch{return!1}}function rp(r,e){let t=Xs(r);if(t)return{traceId:t.traceId,parentSpanId:t.spanId,traceState:Zs(e),traceFlags:t.flags,isRemote:!0}}function jy(r){try{return typeof r.traceparent=="function"}catch{return!1}}function Ky(r){return!!r.attributes&&typeof r.attributes=="object"&&!Array.isArray(r.attributes)&&Array.isArray(r.events)&&r.name!==void 0&&r.kind!==void 0&&r.startTime!==void 0&&r.endTime!==void 0}function li(r,e,t){r[e]!==t&&(r[e]=t)}function Gy(r,e){try{let t=Object.getOwnPropertyDescriptors(r);for(let n of["traceId","spanId","parentSpanId","traceState"])t[n]={value:e[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(r),t)}catch{return r}}var an=class{constructor(e,t,n,s,i,o){this._instance=e,this._config=t,this._logger=n,this._getContext=s,this._contextManager=i,this._onSpanQueued=o,this._queue=[],this._flushTimer=new Tt(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._retryAfter=new bt,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){if(this._instance.isDisabled||this._instance.optedOut)return it(t,this._contextManager.active());let n=Qs(t?.parent);if(n&&typeof n!="string"&&!Ga(n)){if(jy(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),it(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(n,t);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`),it(t,this._contextManager.active());let i=Date.now(),o=zf(t?.startTime,i,this._logger),a=Nf();this._liveSpans.set(a,ci());let c=this._autoContextAttributes();return new tr({traceId:s?.traceId??Lf(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:At(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:Ve({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:o,backdated:o!==i,clockAnchor:er(t?.startTime)===void 0?s?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this.startSpan(e,s);try{let a=on(this._contextManager,o,i);return Zd(a)?a.then(c=>(o.end(),c),c=>{throw this._recordCallbackError(o,c),o.end(),c}):(o.end(),a)}catch(a){throw this._recordCallbackError(o,a),o.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}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=Te,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if(typeof e=="string"){let s=rp(e,t?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(Ga(e))return e.childContext();let n=this._contextManager.active();if(Ga(n))return n.childContext();if(n instanceof sn)return rp(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 t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof tr))return;let{type:n,message:s,stack:i}=Ha(t);e.addEvent("exception",{"exception.type":n,"exception.message":s,...i&&{"exception.stacktrace":i}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=ci()-this._config.maxSpanAgeMs,t=0;for(let[n,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(n),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){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,t);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 t=e.droppedAttributesCount??0,n=e.droppedEventsCount??0,s=0;for(let i of e.events)s+=i.droppedAttributesCount??0;(t||n||s)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${n} events, ${s} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},i={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},o=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},c=e.status&&{...e.status},l=e,u=e;try{for(let p of this._config.beforeSpanSend){let m=p(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:i.attributes,droppedEventsCount:i.events},!Ky(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=At(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=er(u.startTime)??s.startTime,u.endTime=ri(er(u.endTime)??s.endTime,u.startTime);let g=[];for(let p of u.events)try{g.push({...p,name:At(p.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:nn(p.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=g,qf(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,o),u}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,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{li(e,"traceId",t.traceId),li(e,"spanId",t.spanId),li(e,"parentSpanId",t.parentSpanId),li(e,"traceState",t.traceState)}catch{return Gy(e,t)}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),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 t=[];for(let n of e)try{t.push(Qf(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 t}_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 t=Xf(Zf(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),i=this._queue.length,o=0,a=1/0,c=this._generation;try{for(;i>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return o+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,d=Math.max(1,Math.min(u,a,i,this._queue.length)),g=this._queue.slice(0,d),p=this._encodeBatch(g);if(!p.length){this._queue.splice(0,d),i-=d,o+=d,this._resetHeadBatchBudget();continue}let m=ci()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(ep(p,t,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Te,this._resetHeadBatchBudget(),this._queue.splice(0,d),i-=d,o+=d,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(h.kind==="too-large"){if(d===1){this._queue.splice(0,1),i-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=Te,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=Zr(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=ci()+this._nextFlushDelay()),this._headBatchFailures<tp)return this._logger.debug("Span export failed; retrying on the next flush",h.error),o;if(this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${tp} times in a row`),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",h.error),this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._resetHeadBatchBudget(),this._recordDrop(d,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(en(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var cn=class{active(){return this._active}with(e,t){let n=this._active;this._active=e;try{return t()}finally{this._active=n}}};var zy=5e3,Vy=512,qy=2048,Yy=128,Jy=128,Xy=128,Qy=8192,Zy=1e4,eb=36e5;function ot(r,e){return typeof r=="number"&&Number.isInteger(r)&&r>=1?r:e}var np=["service.name","service.version","deployment.environment"];function tb(r){if(!(!r||typeof r!="object"||Array.isArray(r)))try{if(np.every(t=>!(t in r)||typeof r[t]=="string"))return r;let e={...r};for(let t of np)t in e&&typeof e[t]!="string"&&delete e[t];return e}catch{return}}function rb(r,e){if(!r)return[];let t=[r].flat().filter(s=>!!s),n=t.filter(s=>typeof s=="function");return n.length!==t.length&&e?.critical(`beforeSpanSend: ignoring ${t.length-n.length} of ${t.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function za(r,e,t){let n=Ve({...e},tb(r?.resourceAttributes)),s=ot(r?.maxExportBatchSize,Vy);return{serviceName:n?.["service.name"]??r?.serviceName,serviceVersion:n?.["service.version"]??r?.serviceVersion,environment:n?.["deployment.environment"]??r?.environment,resourceAttributes:n,beforeSpanSend:rb(r?.beforeSpanSend,t),maxAttributesPerSpan:ot(r?.maxAttributesPerSpan,Yy),maxEventsPerSpan:ot(r?.maxEventsPerSpan,Jy),maxAttributesPerEvent:Xy,maxAttributeValueLength:ot(r?.maxAttributeValueLength,Qy),flushIntervalMs:ot(r?.flushIntervalMs,zy),maxExportBatchSize:s,maxQueueSize:Math.max(ot(r?.maxQueueSize,qy),s),maxLiveSpans:ot(r?.maxLiveSpans,Zy),maxSpanAgeMs:ot(r?.maxSpanAgeMs,eb)}}var Va=require("node:fs"),op=require("node:fs/promises"),Ya=require("node:path"),ap=require("node:readline"),ui=new q.ReduceableCache(25),ln=new q.ReduceableCache(20),Ja=7,nb=1e3,sb=1e4,qa=10485760;async function cp(r,e=op.open,t){let n={},s;try{s=process.cwd()}catch{}for(let a=r.length-1;a>=0;a--){let c=r[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||lb(l)||ub(c)||!(0,Ya.isAbsolute)(l)&&s===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let i=Object.keys(n);if(i.length==0)return r;let o=[];for(let a of i){let c=lp(a,s);if(c===void 0||ln.get(c))continue;let l=n[a];if(!l)continue;l.sort((g,p)=>g-p);let u=fb(l);if(u.every(g=>db(c,g)))continue;let d=pb(ui,c,{});o.push(ob(a,u,d,c,e,t))}return await Promise.all(o).catch(()=>{}),r&&r.length>0&&ab(r,ui,s),ui.reduce(),r}async function ib(r,e,t){let n,s=!1;try{n=await e(r,Va.constants.O_RDONLY|Va.constants.O_NONBLOCK);let i=await n.stat();return i.isFile()?i.size>qa?void t?.debug(`Skipping source context for oversized file ${r}: ${i.size} bytes exceeds ${qa}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function ob(r,e,t,n,s,i){let o=await ib(r,s,i);if(o===void 0)return void ln.set(n,1);let a=o;return new Promise(c=>{let l=!1;function u(w){l||(l=!0,w?.destroy(),a.close().then(c,c))}let d;try{d=a.createReadStream({autoClose:!1,start:0,end:qa-1})}catch{ln.set(n,1),u();return}let g;try{g=(0,ap.createInterface)({input:d})}catch{ln.set(n,1),u(d);return}let p=0,m=0,h=e[m];if(h===void 0)return void u(d);let _=h[0],E=h[1];function y(){ln.set(n,1),g.close(),g.removeAllListeners(),u(d)}d.on("error",y),g.on("error",y),g.on("close",()=>u(d)),g.on("line",w=>{if(p++,!(p<_)&&(t[p]=gb(w,0),p>=E)){if(m===e.length-1){g.close(),g.removeAllListeners();return}m++;let R=e[m];if(R===void 0){g.close(),g.removeAllListeners();return}_=R[0],E=R[1]}})})}function ab(r,e,t){for(let n of r)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=lp(n.filename,t),i=s===void 0?void 0:e.get(s);if(i===void 0)continue;cb(n.lineno,n,i)}}function cb(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let s=up(r);s<r;s++){let i=t[s];if(i===void 0)return void sp(e);e.pre_context.push(i)}if(t[r]===void 0)return void sp(e);e.context_line=t[r];let n=dp(r);e.post_context=[];for(let s=r+1;s<=n;s++){let i=t[s];if(i===void 0)break;e.post_context.push(i)}}function sp(r){delete r.pre_context,delete r.context_line,delete r.post_context}function lb(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function ub(r){return r.lineno!==void 0&&r.lineno>sb||r.colno!==void 0&&r.colno>nb}function lp(r,e){return(0,Ya.isAbsolute)(r)?JSON.stringify([null,r]):e===void 0?void 0:JSON.stringify([e,r])}function db(r,e){let t=ui.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function fb(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=ip(t),s=[];for(;;){if(e===r.length-1){s.push(n);break}let i=r[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+Ja:(s.push(n),n=ip(i)),e++}return s}function ip(r){return[up(r),dp(r)]}function up(r){return Math.max(1,r-Ja)}function dp(r){return r+Ja}function pb(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function gb(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let s=Math.max(e-60,0);s<5&&(s=0);let i=Math.min(s+140,n);return i>n-5&&(i=n),i===n&&(s=Math.max(i-140,0)),t=t.slice(s,i),s>0&&(t=`...${t}`),i<n&&(t+="..."),t}var rr=require("path");function fp(r=process.cwd()){let e=rr.sep==="\\",t=s=>e?s.replace(/\\/g,"/"):s,n=t(r);return async s=>{for(let i of s)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,rr.isAbsolute)(i.filename)&&(i.filename=t((0,rr.relative)(n,t(i.filename))));return s}}var pp="5.56.1";var Ye={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var at=class r{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,t={}){let n=this._flags[e];return this._recordAccess(e),n?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let s of e){let i=this._flags[s];i?t[s]=i:n.push(s)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,s]of Object.entries(this._flags)){let i=s.enabled===!1?!1:s.variant??!0;e[`$feature/${n}`]=i,s.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({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 t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,s={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(Ye.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(Ye.QUOTA_LIMITED),t===void 0&&i.push(Ye.FLAG_MISSING),i.length>0&&(s.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}};var mb=6e4;function gp(r){return r==="client"||r==="server"?r:"all"}function hb(r,e){return r===e||r==="all"||e==="all"}var nr=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function _b(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var He=class r extends Error{constructor(e){super(e),_b(this,r)}},di=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:s,host:i,customHeaders:o,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=o,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(e,t={},n={},s={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:s,evaluationCache:i}}async getFeatureFlag(e,t,n={},s={},i={}){await this.loadFeatureFlags();let o,a;if(!this.loadedSuccessfullyOnce)return o;if(a=this.featureFlagsByKey[e],a!==void 0){let c=this.createEvaluationContext(t,n,s,i);try{o=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(l){l instanceof He||l instanceof v?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${e}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${l}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},s={},i=this.featureFlags.length==0,o=t?t.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(o.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(s[c.key]=u)}catch(l){l instanceof He||l instanceof v?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),i=!0}})),{response:n,payloads:s,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:s,skipLoadCheck:i=!1}=n;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};t=this.withEvaluationSnapshot(t),e=t.definitions.featureFlagsByKey[e.key]??e;let o;o=s!==void 0?s:await this.computeFlagValueLocally(e,t);let a=Pa(e.filters?.payloads,o);return{value:o,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:s,personProperties:i,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new v("Flag has experience continuity enabled");let c=(e.filters||{}).aggregation_group_type_index;if(c!=null){let l=t.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${e.key}`)),new v("Flag has unknown group type index");if(!(l in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=o[l];return await this.matchFeatureFlagProperties(e,s[l],u,t)}{let l=this.getBucketingValueForFlag(e,n,i);if(l===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 v(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let s=n?.$device_id;return s==null||s===""?void 0:s}return t}async evaluateFlagDependency(e,t,n){let{evaluationCache:s}=n,i=e.key;if(!n.definitions.featureFlagsByKey)throw new v("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new v(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new v(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new v(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let c of o){if(!(c in s)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let d=await this.computeFlagValueLocally(u,n);s[c]=d}catch(d){throw new v(`Error evaluating flag dependency '${c}' for flag '${i}': ${d}`)}else s[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))s[c]=!1;else throw new v(`Missing flag dependency '${c}' for flag '${i}'`)}if(s[c]==null)throw new v(`Dependency '${c}' could not be evaluated`)}let a=s[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,s){s=this.withEvaluationSnapshot(s);let i=e.filters||{},o=await Ca(i.holdout,t);if(o!==void 0)return o;let a=i.groups||[],c=i.aggregation_group_type_index,l=i.early_exit??!1,{groups:u,groupProperties:d}=s,g=!1,p;for(let m of a)try{let h=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,_=n,E=t;if(h!==c&&h!=null){let w=s.definitions.groupTypeMapping[String(h)];if(!w||!(w in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(w in d)){g=!0;continue}_=d[w],E=u[w]}let y=await this.isConditionMatch(e,E,m,_,s);if(y==="match"){let w=m.variant,R=i.multivariate?.variants||[];p=w&&R.some(P=>P.key===w)?w:await this.getMatchingVariant(e,E)||!0;break}if(l&&y==="out_of_rollout_bound"){if(g)break;return!1}}catch(h){if(h instanceof He)throw h;if(h instanceof v)g=!0;else throw h}if(p!==void 0)return p;if(g)throw new v("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,s,i){i=this.withEvaluationSnapshot(i);let o=i.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,d=!1;if(u==="cohort"){let g=await hp(l,s,o.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,s,i),o.propertyMatchingVersion);d=l.operator==="not_in"?!g:g}else d=u==="flag"?await this.evaluateFlagDependency(l,s,i):mp(l,s,c,o.propertyMatchingVersion);if(!d)return"no_match"}if(a==null)return"match"}return a!=null&&await Yr(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return Ia(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return Ys(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let t=new Set(this.evaluationContexts);return e.filter(n=>{let s=n.evaluation_contexts??n.evaluation_tags;return!s||s.length===0?!0:s.some(i=>t.has(i))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?gp(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>hb(gp(t.evaluation_runtime),e)).map(t=>t.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags);this.featureFlags=t,this.featureFlagsByKey=t.reduce((s,i)=>(s[i.key]=i,s),{});let n=new Set(t.map(s=>s.key));this.filteredOutFlagKeys=new Set(e.flags.filter(s=>!n.has(s.key)).map(s=>s.key)),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 t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.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 t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!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(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).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(mb,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{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 t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new nr(`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 nr(`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 nr(`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 t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let s=n.group_type_mapping||{},i=n.minimal_flag_called_events===!0,o={flags:n.flags??[],group_type_mapping:s,cohorts:n.cohorts||{},minimal_flag_called_events:i,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:s,minimalFlagCalledEvents:i};if(this.updateFlagState(o),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(o)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof nr&&this.onError?.(e)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=ce(()=>{i.abort()},this.timeout),t.signal=i.signal}let s=()=>clearTimeout(n);try{let i=this.fetch,o=await i(e,t);return o.status!==200?(s(),o):{status:o.status,headers:o.headers,body:o.body,text:async()=>{try{return await o.text()}finally{s()}},json:async()=>{try{return await o.json()}finally{s()}}}}catch(i){throw s(),i}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await st(t,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};function mp(r,e,t,n){return Oa(r,e,{warnFunction:t,propertyMatchingVersion:n})}function Eb(r,e){if(!(r in e))throw new He(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function hp(r,e,t,n=!1,s,i){let o=String(r.value);Eb(o,t);let a=t[o];return _p(a,e,t,n,s,i)}async function _p(r,e,t,n=!1,s,i){if(!r)return!0;let o=r.type,a=r.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await _p(l,e,t,n,s,i);if(o==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof He)throw u;if(u instanceof v)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new v("Can't match cohort without a given cohort property value");return o==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await hp(l,e,t,n,s,i);else if(l.type==="flag"){if(!s)throw new v(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await s(l)}else u=mp(l,e,void 0,i);let d=l.negation||!1;if(o==="AND"){if(!u&&!d||u&&d)return!1}else if(u&&!d||!u&&d)return!0}catch(u){if(u instanceof He)throw u;if(u instanceof v)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new v("can't match cohort without a given cohort property value");return o==="AND"}var Sb=["--unhandled-rejections","--unhandled_rejections"],yb=new Set(["throw","strict","warn","warn-with-error-code","none"]),bb=[...globalThis.process?.execArgv??[]],wb=globalThis.process?.env?.NODE_OPTIONS;function Tb(r){let e=[],t="",n=!1;for(let s=0;s<r.length;s++){let i=r[s];i==="\\"&&n&&s+1<r.length?t+=r[++s]:i!==" "||n?i==='"'?n=!n:t+=i:t&&(e.push(t),t="")}return t&&e.push(t),e}function Ep(r){let e;for(let t=0;t<r.length;t++){let n=r[t],s=Sb.find(o=>n===o||n.startsWith(`${o}=`));if(!s)continue;let i=n===s?r[++t]:n.slice(s.length+1);yb.has(i)&&(e=i)}return e}function Ab(r=bb,e=wb){return Ep(r)??Ep(Tb(e??""))??"throw"}var Sp=Ab();function yp(r,e,t){r(e,{mechanism:{type:t==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Rb(r,e){let t=!1;return Object.assign((n,s)=>{let i=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length;yp(r,n,s),!t&&i===0&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function bp(r,e,t=Sp){let n=globalThis.process;if(n){if(t==="strict")return void n.on("uncaughtExceptionMonitor",(s,i)=>yp(r,s,i));n.on("uncaughtException",Rb(r,e))}}function wp(r,e=Sp){let t=globalThis.process;!t||e==="throw"||e==="strict"||e==="warn-with-error-code"||t.on("unhandledRejection",n=>{r(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var vb=2e3,Xa=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Ps({...kd(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return xr(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,s,i){let o={...i},a=e.buildFromUnknown(t,n);a.$exception_list=await e.modifyFrames(a.$exception_list);let c=q.getInjectedReleaseId();return c&&(o.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(bp(this.onException.bind(this),this.onFatalError.bind(this)),wp(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(vb),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},vt=Xa;var Mb=/^[0-9a-f]{32}$/i,Ob=/^[0-9a-f]{16}$/i,Cb;async function Tp(){try{let e=(await(Cb??=import("@opentelemetry/api"))).trace.getActiveSpan()?.spanContext(),t=e?.traceId,n=e?.spanId;if(typeof t=="string"&&typeof n=="string"&&Mb.test(t)&&Ob.test(n)&&!/^0+$/.test(t)&&!/^0+$/.test(n))return{$trace_id:t.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var fi=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function Ib(r){return r==="v0"||r==="v1"}function Ap(){let r="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Ib(r)?r:"v0"}var Pb="$ai_",un="analytics";function Rp(r){return typeof r.event=="string"&&r.event.startsWith(Pb)}var sr=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:s}){super(r.buildMessage(e,t,n,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=s}static buildMessage(e,t,n,s){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return s instanceof Error&&(i+=` (${s.message})`),i}};function Qa(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function kb(r){return typeof r=="string"?r:void 0}var xb=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Qa},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Qa},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Qa},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:kb}],Db=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Lb(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Nb(r){if(typeof r=="string"){let t=new Date(r);if(Number.isNaN(t.getTime()))return new Date().toISOString();let n=t.toISOString(),s=r.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function vp(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function Fb(r){let t={...Lb(r.properties)?r.properties:{}},n={};for(let{property:i,optionKey:o,coerce:a}of xb)if(i in t){let c=a(t[i]);c!==void 0&&(n[o]=c),delete t[i]}let s={};for(let{property:i,field:o}of Db)if(i in t){let a=t[i];typeof a=="string"&&(s[o]=a),delete t[i]}return delete t.$lib,delete t.$lib_version,vp(t,"$set",r.$set),vp(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:Nb(r.timestamp),...s,options:n,properties:t}}function Mp(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(Fb)};return t&&(n.historical_migration=!0),n}var Ub="/i/v1/analytics/events",$b=3e4,Bb=new Set([408,500,502,503,504]),pi=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??$b,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(s=>ce(s,n))),this.generateRequestId=t.generateRequestId??ae,this.compress=t.compress??zr}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=Mp(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${Ub}`,o=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,d=rt({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),g,p;try{g=await this.sendOnce(i,d,l,t);let{response:m,signal:h}=g,{status:_}=m;if(_<200||_>=300)if(!u&&Bb.has(_)){let E=this.parseRetryAfter(m);await g.waitFor(g.cancelBody()).catch(()=>{}),p=this.backoffDelay(l,E)}else{let E=await this.buildHttpError(m,_,g.waitFor);return this.surfaceBatchFailure(t,o,a,E)}else{let E;try{E=await g.waitFor(this.parseResponse(m))}catch(R){if(h.aborted)throw R;return this.surfaceBatchFailure(t,o,a,new Error(`Capture V1 returned an unparseable ${_} response body`))}let y=this.classify(a,E,o);if(y.length===0)return this.surfacePartialDrops(t,o);if(u)return void this.onError(new sr({requestId:t,drops:o,retryExhausted:y.map(R=>R.uuid)}));a=y;let w=this.parseRetryAfter(m);p=this.backoffDelay(l,w)}}catch(m){if(g&&!g.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(t,o,a,m);p=this.backoffDelay(l)}finally{g?.cleanup()}p!==void 0&&await this.sleep(p)}}async sendOnce(e,t,n,s){let i=this.buildHeaders(n,s),o=t;if(this.config.compressionEnabled){let d=await this.compress(t,this.config.isDebug);d!==null&&(o=d,i["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((d,g)=>{l=ce(()=>{let p=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);p.name="AbortError",g(p),a.abort(p)},this.config.requestTimeoutMs)});try{let d=this.fetchFn(e,{method:"POST",headers:i,body:o,signal:a.signal}),g=!1;d.then(E=>{a.signal.aborted&&!g&&this.cancelBody(E)}).catch(()=>{});let p=await Promise.race([d,u]);g=!0,c="while reading the response body";let m=!1,h,_=()=>h??=this.cancelBody(p);return{response:p,signal:a.signal,waitFor:E=>Promise.race([E,u]),cancelBody:_,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&_())}}}catch(d){throw clearTimeout(l),d}}buildHeaders(e,t){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":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(s["User-Agent"]=this.config.userAgent),s}classify(e,t,n){let s=t.results??{},i=[];for(let o of e){let a=s[o.uuid];a&&(a.result==="drop"?n.push({uuid:o.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(o))}return i}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let o=parseInt(n,10);return Number.isFinite(o)&&o>0?1e3*o:void 0}let s=Date.parse(n);if(Number.isNaN(s))return;let i=s-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);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,t,n){let s="";try{s=(await n(e.text())).slice(0,512)}catch{}let i=s?`: ${s}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,n,s){this.onError(new sr({requestId:e,drops:t,retryExhausted:n.map(i=>i.uuid),cause:s}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new sr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var Mt="ai-capture",gi="/i/v0/ai/batch/";var Hb=new TextEncoder;function ec(r){return Hb.encode(rt(r)).length}function Op(r,e=8388608,t=5242880){let n=[],s=[],i=[],o=0;for(let a of r){if(a===void 0)continue;let c=ec(a);if(c>e){s.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}i.length>0&&o+c>t&&(n.push(i),i=[],o=0),i.push(a),o+=c}return i.length>0&&n.push(i),{batches:n,dropped:s}}var jb=100,Cp=3e4,Kb=5e4,Gb=50,zb=500,Vb="https://us.i.posthog.com",Ip=new Set;function hi(r,e){Ip.has(r)||(Ip.add(r),console.warn(`[PostHog] ${e}`))}function qb(r){return typeof r=="string"?r.trim():""}function Yb(r){return(typeof r=="string"?r.trim():"")||void 0}function Jb(r){return(typeof r=="string"?r.trim():"")||Vb}function Xb(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function Qb(r){if(!r)return{};let e={};for(let[n,s]of Object.entries(r))e[`$feature/${n}`]=s;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var _i=class extends Vr{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){let n=qb(e),s={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:Jb(t.host),personalApiKey:Yb(t.secretKey??t.personalApiKey)};if(super(n,s),this._memoryStorage=new fi,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=Ap(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,jb):s.featureFlagsPollingInterval===null?null:Cp,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){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 di({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:n,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:o=>{this._events.emit("error",o)},onLoad:o=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:o=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments}))}this.errorTracking=new vt(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||Kb}enqueue(e,t,n,s){super.enqueue(e,t,n,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:Nr([t,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 t=this._flushEventsAndSpans(e),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let o,a=new Promise(c=>{o=c});try{e(a)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??zb,s=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??Gb;this._waitUntilCycle.timer=ce(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&Rp(e)?"ai":un}persistedQueueKeyForRoute(e){return e===Mt?de.AiCaptureQueue:e==="ai"?de.AiQueue:de.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[un,"ai"]:[un];return this._aiCaptureRouteActive&&e.push(Mt),e}getBatchEndpointPath(e){return e===Mt?gi:super.getBatchEndpointPath(e)}async sendBatch(e,t,n=un){if(n===Mt)return this.sendAiCaptureBatch(e,t);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let s=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,t){let{batches:n,dropped:s}=Op(e);for(let{event:i,bytes:o}of s){let a=`Event ${i} (${o} bytes) exceeds the ${8388608/1048576}MiB limit for ${gi}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let i of n)await this.sendAiSubBatch(i,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,Mt)}catch(n){if(!Qt(n))throw n;if(e.length===1){let[i]=e,a=`Event ${typeof i.event=="string"?i.event:"unknown"} (${ec(i)} bytes) was rejected with 413 by ${gi} 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),t),await this.sendAiSubBatch(e.slice(s),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new pi({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,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return pp}get metrics(){return this._metrics||(this._metrics=new rn(this,ti(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new cn}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 an(this,za(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,t){return this._tracesPipeline?.startSpan(e,t)??it(t,this._spanContextManager.active())}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this._tracesPipeline;return o?s?o.withSpan(e,s,i):o.withSpan(e,i):on(this._spanContextManager,it(s,this._spanContextManager.active()),i)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,s,i){return this.addPendingPromise(this._prepareEventMessage(t,s).then(({distinctId:o,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},d={distinctId:o,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,d,u,i):this.enqueue(e,d,u,i)}).catch(o=>{o&&console.error(o)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}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 t=wt(e.uuid,ae);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=wt(e.uuid,ae);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){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,t,void 0,Mt)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let s={};Object.keys(t).length>0&&(s.$set=t),Object.keys(n).length>0&&(s.$set_once=n),this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:t}){let n=Xb(t);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=Cp){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{s(),t(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),s(),t(i>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let S=this._flagOverrides[e];if(S===void 0)return;let T=this._payloadOverrides?.[e];return{key:e,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:T}}let{groups:o,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,d=this.addLocalPersonAndGroupProperties(t,o,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p,m=!1,h,_,E,y,w,R,P;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let S=this.featureFlagsPoller?.featureFlagsByKey[e];if(S)try{let T=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(S,g,{matchValue:s});if(T){m=!0;let b=T.value;y=S.id,R="Evaluated locally",P=S.has_experiment,p={key:e,enabled:b!==!1,variant:typeof b=="string"?b:void 0,payload:T.payload??void 0,reason:R,reasonCode:S.active===!1?"flag_disabled":void 0}}}catch(T){if(T instanceof He||T instanceof v)this._logger?.info(`${T.name} when computing flag locally: ${e}: ${T.message}`);else throw T}}if(!m&&!c){let S=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,a,[e]);if(S===void 0)E=Ye.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=S.minimalFlagCalledEvents===!0,h=S.requestId,_=S.evaluatedAt;let T=[];S.errorsWhileComputingFlags&&T.push(Ye.ERRORS_WHILE_COMPUTING),S.quotaLimited?.includes("feature_flags")&&T.push(Ye.QUOTA_LIMITED);let b=S.flags[e];if(b===void 0)T.push(Ye.FLAG_MISSING);else{y=b.metadata?.id,w=b.metadata?.version,R=b.reason?.description??b.reason?.code,P=b.metadata?.has_experiment;let C;if(b.metadata?.payload!==void 0)try{C=JSON.parse(b.metadata.payload)}catch{C=b.metadata.payload}p={key:e,enabled:b.enabled,variant:b.variant??void 0,payload:C,reason:R,reasonCode:b.reason?.code}}T.length>0&&(E=T.join(","))}}if(i){let S=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,T={$feature_flag:e,$feature_flag_response:S,$feature_flag_id:y,$feature_flag_version:w,$feature_flag_reason:R,locally_evaluated:m,[`$feature/${e}`]:S,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():_};if(P!==void 0&&(T.$feature_flag_has_experiment=P),m&&this.featureFlagsPoller){let b=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();b!==void 0&&(T.$feature_flag_definitions_loaded_at=b)}E&&(T.$feature_flag_error=E),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:S,groups:o,disableGeoip:a,properties:T})}return p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[e]}),p}async getFeatureFlag(e,t,n){hi("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,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s!==void 0)return s.enabled===!1?!1:s.variant??!0}async getFeatureFlagPayload(e,t,n,s){if(hi("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...s,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:s,options:i}=this._resolveDistinctId(t,n);return s?this._getFeatureFlagResult(e,s,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){hi("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,t,{...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,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);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,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:o,flagKeys:a}=s||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),m={},h={},_=!0;if(p&&(m=p.response,h=p.payloads,_=p.fallbackToFlags),_&&!c){let E=await super.getFeatureFlagsAndPayloadsStateless(g.distinctId,g.groups,l,u,o,a);m={...m,...E.flags||{}},h={...h,...E.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,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:o}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=a?new Set(a):void 0,m={},h,_,E=!1,y=!1,w=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),R=new Set;if(w)for(let[S,T]of Object.entries(w.response)){let b=this.featureFlagsPoller?.featureFlagsByKey[S];m[S]={key:S,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:w.payloads[S],id:b?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:b?.has_experiment},R.add(S)}let P=p!==void 0&&Array.from(p).some(S=>this.featureFlagsPoller?.featureFlagsByKey[S]===void 0);if((w?w.fallbackToFlags||P:!0)&&!c){let S=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,o,a);if(S){this._minimalFlagCalledEvents=S.minimalFlagCalledEvents===!0,h=S.requestId,_=S.evaluatedAt,E=!!S.errorsWhileComputingFlags,y=Array.isArray(S.quotaLimited)&&S.quotaLimited.includes("feature_flags");for(let[T,b]of Object.entries(S.flags)){if(R.has(T))continue;let C;if(b.metadata?.payload!==void 0)try{C=JSON.parse(b.metadata.payload)}catch{C=b.metadata.payload}m[T]={key:T,enabled:b.enabled,variant:b.variant,payload:C,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[S,T]of Object.entries(this._flagOverrides)){if(T===void 0){delete m[S];continue}let b=m[S];m[S]={key:S,enabled:T!==!1,variant:typeof T=="string"?T: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[S,T]of Object.entries(this._payloadOverrides)){let b=m[S];b&&(m[S]={...b,payload:T})}if(p!==void 0)for(let S of Object.keys(m))p.has(S)||delete m[S];return new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:m,requestId:h,evaluatedAt:_,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:E,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:s,groups:i,disableGeoip:o,properties:a}=e,c=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([d],[g])=>d<g?-1:d>g?1:0))}`:"",l=`${n}_${s}${c}`,u=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,u),!u.has(l)){for(u.add(l);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:t,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:o})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=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=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(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 t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await st(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await st(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;s=ce(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(t,n)}catch(i){this._events.emit("error",i);return}finally{s&&clearTimeout(s)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},s={};for(let[i,o]of Object.entries(e))if(Cd(o)&&t&&i in t){let a={};for(let[c,l]of Object.entries(o))a[String(c)]=String(l);s[String(i)]=a}else n[String(i)]=String(o);return{personProperties:n,groupProperties:s}}async getFeatureFlagsForEvent(e,t,n,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=s?.personProperties||{},o=s?.groupProperties||{},a=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,i,o,n)).flags}addLocalPersonAndGroupProperties(e,t,n,s){let i={...n||{}},o={};if(t)for(let a of Object.keys(t))o[a]={$group_key:t[a],...s?.[a]||{}};return{allPersonProperties:i,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,s){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,t,n,s,i){if(!vt.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");this.addPendingPromise(vt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,n).then(a=>this._capturePreparedEvent({...a,uuid:s,flags:i},!1)))}}async captureExceptionImmediate(e,t,n,s){if(!vt.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(vt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,n).then(o=>this.captureImmediate({...o,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:s,properties:i,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d}=e,g=this.context?.get(),p=t.includeContextProperties??!0,m=n||g?.distinctId,h=p?{...this.props,...g?.properties||{},...i||{}}:{...i||{}};s==="$exception"&&!("$trace_id"in h||"$span_id"in h)&&Object.assign(h,await Tp()),m||(m=ae(),h.$process_person_profile=!1),p&&g?.sessionId&&!h.$session_id&&(h.$session_id=g.sessionId);let _=this._shouldSendMinimalFlagCalledEvent(s,h)?Kr(h):h,E=this._runBeforeSend({distinctId:m,event:s,properties:_,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d});if(!E)return Promise.reject(null);let y=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){hi("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let w=typeof c=="object"?c:void 0,R=await this.getFeatureFlagsForEvent(E.distinctId,o,u,w);return Qb(R)}return{}}).catch(()=>({})).then(w=>{let R=E.groups||o;return{...w,...E.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return E.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof y.$raw_user_agent=="string"&&Pd(y.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(E.event="$bot_pageview",y.$browser_type="bot"),{distinctId:E.distinctId,event:E.event,properties:y,options:{timestamp:E.timestamp,disableGeoip:E.disableGeoip,uuid:E.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],s=e;for(let i of n)try{if(s=i(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let o=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}catch(o){return this._logger.error(`Error in before_send function for event '${e.event}':`,o),null}return s}};var Pp=require("node:async_hooks"),Ei=class{constructor(){this.storage=new Pp.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.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 kp=require("node:async_hooks"),Si=class{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new kp.AsyncLocalStorage}};var xp=require("node:zlib"),Dp=require("node:util"),Zb=(0,Dp.promisify)(xp.gzip);async function Lp(r,e=!0){try{let t=await Zb(r);return new Uint8Array(t)}catch(t){return e&&console.error("Failed to gzip compress data",t),null}}var yi=require("node:os");function Np(){let r,e;try{r=(0,yi.platform)(),e=(0,yi.release)()}catch{}return La(r,e)}var Fp="posthog-node";function ew(r,{organization:e,projectId:t,prefix:n,severityAllowList:s=["error"],sendExceptionsToPostHog:i=!0}={}){return o=>{if(!(s==="*"||s.includes(o.level)))return o;o.tags||(o.tags={});let c=o.tags[tc.POSTHOG_ID_TAG];if(c===void 0)return o;let l=r.options.host??"https://us.i.posthog.com",u=new URL(`/project/${r.apiKey}/person/${c}`,l).toString();o.tags["PostHog Person URL"]=u;let d=o.exception?.values||[],g=d.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(_=>({..._,platform:"node:javascript"}))}:void 0})),p={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:g,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags},m=q.getInjectedReleaseId();return m&&(p.$release_id=m),e&&t&&(p.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+o.event_id),i&&r.capture({event:"$exception",distinctId:c,properties:p}),o}}var tc=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,n,s,i){this.name=Fp,this.name=Fp,this.setupOnce=function(o,a){let c=a()?.getClient()?.getDsn()?.projectId;o(ew(e,{organization:t,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:i??!0}))}}};var bi=class extends _i{getLibraryId(){return"posthog-node"}compressPayload(e){return Lp(e,this.isDebug)}initializeContext(){return new Ei}initializeSpanContextManager(){return new Si}hostResourceAttributes(){return Np()}createErrorPropertiesBuilder(){return new q.ErrorPropertiesBuilder([new q.EventCoercer,new q.ErrorCoercer,new q.ObjectCoercer,new q.StringCoercer,new q.PrimitiveCoercer],q.createStackParser("node:javascript",q.nodeStackLineParser),[Ad(),e=>cp(e,void 0,this._logger),fp()])}};var Je=new Map,ct=null,dn=new Map,Ce=null,Ie=null,tw=300*1e3,rw=3600*1e3,nw=1e3;function Up(r,e){let{records:t,windowStartTs:n,windowSeq:s}=r,i=t.length,o=0,a=0,c=0,l=0,u=0,d=0,g=0,p=0,m=0,h=0,_=0,E=0,y=0,w=0,R=0,P=0,O=0,S=0,T=new Map,b=new Map,C,Ii,uc,dc;for(let A of t)typeof A.tokens_input=="number"&&Number.isFinite(A.tokens_input)&&(o+=A.tokens_input),typeof A.tokens_output=="number"&&Number.isFinite(A.tokens_output)&&(a+=A.tokens_output),typeof A.cost_usd=="number"&&Number.isFinite(A.cost_usd)&&(c+=A.cost_usd),typeof A.duration_ms=="number"&&Number.isFinite(A.duration_ms)&&(l+=A.duration_ms,u++),typeof A.compression_ms=="number"&&Number.isFinite(A.compression_ms)&&(d+=A.compression_ms,g++),A.outcome==="ok"?p++:A.outcome==="error"?m++:A.outcome==="aborted"?(h++,A.abort_reason==="deadline_exceeded"&&_++):A.outcome==="invalid_output"&&E++,typeof A.abort_reason=="string"&&A.abort_reason&&b.set(A.abort_reason,(b.get(A.abort_reason)??0)+1),typeof A.model=="string"&&A.model&&T.set(A.model,(T.get(A.model)??0)+1),typeof A.ide=="string"&&A.ide&&(C=A.ide),typeof A.provider=="string"&&A.provider&&(Ii=A.provider),typeof A.observed_model=="string"&&A.observed_model&&(uc=A.observed_model),typeof A.observed_billing=="string"&&A.observed_billing&&(dc=A.observed_billing),typeof A.count=="number"&&Number.isFinite(A.count)&&(y+=A.count),typeof A.obs_type_bugfix=="number"&&Number.isFinite(A.obs_type_bugfix)&&(w+=A.obs_type_bugfix),typeof A.obs_type_discovery=="number"&&Number.isFinite(A.obs_type_discovery)&&(R+=A.obs_type_discovery),typeof A.obs_type_decision=="number"&&Number.isFinite(A.obs_type_decision)&&(P+=A.obs_type_decision),typeof A.obs_type_refactor=="number"&&Number.isFinite(A.obs_type_refactor)&&(O+=A.obs_type_refactor),typeof A.obs_type_other=="number"&&Number.isFinite(A.obs_type_other)&&(S+=A.obs_type_other);let lt={count:i,total_tokens_input:o,total_tokens_output:a,total_cost_usd:c,avg_duration_ms:u>0?l/u:0,avg_compression_ms:g>0?d/g:0,outcomes_ok:p,outcomes_error:m,outcomes_aborted:h,outcomes_aborted_deadline_exceeded:_,outcomes_invalid_output:E,observations_created:y,obs_type_bugfix:w,obs_type_discovery:R,obs_type_decision:P,obs_type_refactor:O,obs_type_other:S,window_start_ts:n,rollup_reason:e,window_seq:s};if(T.size>0){let A="",or=0;for(let[Pi,ar]of T)ar>or&&(or=ar,A=Pi);lt.top_model=A}if(b.size>0){let A="",or=0;for(let[Pi,ar]of b)ar>or&&(or=ar,A=Pi);lt.top_abort_reason=A}return C&&(lt.ide=C),Ii&&(lt.provider=Ii),lt.observed_model=uc??"unknown",lt.observed_billing=dc??"unknown",lt}function sw(r){let{records:e,windowStartTs:t}=r,n=e.length,s=0,i=0,o=0,a=0,c=0,l=0;for(let u of e){let d=u.tokens_injected;typeof d=="number"&&Number.isFinite(d)&&(s+=d,i++),typeof u.observation_count=="number"&&Number.isFinite(u.observation_count)&&(c+=u.observation_count),typeof u.tokens_saved_vs_naive=="number"&&Number.isFinite(u.tokens_saved_vs_naive)&&(l+=u.tokens_saved_vs_naive),u.outcome==="ok"?o++:u.outcome==="error"&&a++}return{count:n,total_tokens:s,avg_tokens:i>0?s/i:0,total_observations_injected:c,total_tokens_saved_vs_naive:l,outcomes_ok:o,outcomes_error:a,window_start_ts:t}}var Ct={record(r,e,t){let n=Date.now();if(r==="work_state_usage"){let s={platform:t.platform,agent_role:t.agent_role,instruction_state:t.instruction_state},i=JSON.stringify(s),o=dn.get(i)??{...s,window_start_ts:n};for(let[a,c]of Object.entries(t))a.endsWith("_count")&&typeof c=="number"&&Number.isFinite(c)&&c>=0&&(o[a]=Number(o[a]??0)+c);dn.set(i,o)}else if(r==="session_compressed"){if(typeof e!="number")return;let s=Je.get(e);s||(s={records:[],windowStartTs:n,windowSeq:0},Je.set(e,s)),s.records.push(t)}else ct||(ct={records:[],windowStartTs:n}),ct.records.push(t)},flushSession(r,e){let t=Je.get(r);if(!t||t.records.length===0)return Je.delete(r),!1;let n=Up(t,e);return Je.delete(r),Ot("observer_turn_rollup",n),!0},drainAllSessions(r){for(let e of Array.from(Je.keys()))Ct.flushSession(e,r)},safetyFlush(){let r=Date.now();for(let[e,t]of Array.from(Je.entries())){let n=r-t.windowStartTs>=rw,s=t.records.length>=nw;if(!n&&!s||t.records.length===0)continue;let i=Up(t,"safety_flush");Ot("observer_turn_rollup",i),t.records=[],t.windowStartTs=r,t.windowSeq+=1}},flush(){for(let r of dn.values())Ot("work_state_usage_rollup",r);if(dn.clear(),ct&&ct.records.length>0){let r=sw(ct);ct=null,Ot("context_injected_rollup",r)}},start(r=300*1e3){Ce===null&&(Ce=setInterval(()=>{Ct.flush()},r),Ce&&typeof Ce.unref=="function"&&Ce.unref()),Ie===null&&(Ie=setInterval(()=>{Ct.safetyFlush()},tw),Ie&&typeof Ie.unref=="function"&&Ie.unref())},stop(){Ce!==null&&(clearInterval(Ce),Ce=null),Ie!==null&&(clearInterval(Ie),Ie=null)},__resetForTests(){Ce!==null&&(clearInterval(Ce),Ce=null),Ie!==null&&(clearInterval(Ie),Ie=null),Je.clear(),ct=null,dn.clear()},__activeSessionBucketCount(){return Je.size}};M();var rc=null,iw=!1,ow=3e4,wi=null;function nc(){let r=Date.now();if(wi&&r<wi.expiresAt)return wi.value;let e=Nn(process.env,hr());return wi={value:e,expiresAt:r+ow},e}function Bp(){return nc()}var aw=!1;function cw(){if(!rc){let r=aw&&dl(process.env)&&nc();rc=new bi($n(),{host:Bn(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:r,before_send:_w})}return rc}var lw=6e4,uw=500,fn=new Map;function dw(r,e,t){let n="";try{let s=(t||"").split(`
33
- `).map(i=>i.trim()).filter(Boolean);n=s.find(i=>i.startsWith("at "))??s[1]??""}catch(s){let i=s instanceof Error?s:new Error(String(s));f.warn("SYSTEM","Telemetry: stack parse failed while fingerprinting; using empty top frame",void 0,i),n=""}return`${r}::${_l(e)}::${n}`.slice(0,400)}function fw(r,e){try{return pw(r,e)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: error rate-limit bookkeeping failed; failing closed (event dropped)",void 0,n),{send:!1,count:0}}}function pw(r,e){let t=fn.get(r);if(!t){if(fn.size>=uw){let n=null,s=1/0;for(let[i,o]of fn){let a=Math.max(o.lastSentTs,o.firstTs);a<s&&(s=a,n=i)}n!==null&&fn.delete(n)}return t={count:1,firstTs:e,lastSentTs:e},fn.set(r,t),{send:!0,count:1}}if(t.count+=1,e-t.lastSentTs>=lw){t.lastSentTs=e;let n=t.count;return t.count=0,{send:!0,count:n}}return{send:!1,count:t.count}}var $p="__cm_rate_limited";function gw(r){try{return typeof r!="string"||r.length===0?"":to(eo(r))}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: frame filename redaction failed; stripping value entirely",void 0,t),""}}function mw(r){let e=r.$exception_list;if(Array.isArray(e))for(let t of e){if(!t||typeof t!="object")continue;let n=t;typeof n.value=="string"&&(n.value=hl(n.value));let i=n.stacktrace?.frames;if(Array.isArray(i))for(let o of i){if(!o||typeof o!="object")continue;let a=o;delete a.context_line,delete a.pre_context,delete a.post_context,typeof a.filename=="string"&&(a.filename=gw(a.filename))}}}function hw(r){try{let e=[],t=i=>{typeof i=="string"&&e.push(i)};t(r.$exception_message),t(r.$exception_type),t(r.error_message),t(r.error_type);let n=r.$exception_list;if(Array.isArray(n))for(let i of n)i&&typeof i=="object"&&(t(i.value),t(i.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 _w(r){try{if(!r||typeof r!="object")return r;let e=r;if(e.event!=="$exception")return r;let t=e.properties??{};if(hw(t))return null;if(t[$p]){try{delete t[$p],e.properties=t}catch{}return r}mw(t),t.$process_person_profile=!1,e.properties=t;let n="Error",s="",i="";try{let c=t.$exception_list;if(Array.isArray(c)&&c[0]&&typeof c[0]=="object"){let l=c[0];typeof l.type=="string"&&(n=l.type),typeof l.value=="string"&&(s=l.value);let u=l.stacktrace?.frames;Array.isArray(u)&&u.length>0&&(i="at "+JSON.stringify(u[u.length-1]).slice(0,200))}}catch{}typeof t.$exception_type=="string"&&(n=t.$exception_type),typeof t.$exception_message=="string"&&(s=t.$exception_message);let o=dw(n,s,i),a=fw(o,Date.now());if(!a.send)return null;try{t.occurrence_count=a.count,e.properties=t}catch{}return r}catch{return null}}function Ot(r,e,t){try{Ew(r,e,t)}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","Telemetry: captureEvent failed; event dropped",{event:r},s)}}function Ew(r,e,t){if(iw||!nc())return;let n=Un({...Hn(),...e??{}});if(t?.person?n.$set=Wn(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
34
- `);return}cw().capture({distinctId:Fn(),event:r,properties:n})}var Sw=["agent-cost-report","babysit","build","build-and-release","ccs-align","childhood","cloud-sync","design-is","do","handoff","how-it-works","knowledge-agent","learn-codebase","make-plan","mem-search","mode-creator","oh-my-issues","pathfinder","release","screenpipe","smart-explore","standup","timeline-report","version-bump","weekly-digests","what-the","wowerpoint"],yw=new Set(Sw),Wp={skill_id:"other",skill_source:"third_party"};function Hp(r){let e=bw(r);return e&&yw.has(e)?{skill_id:e,skill_source:"first_party"}:Wp}function jp(r,e){if(r==="Skill"&&!(!e||typeof e!="object"))return e.skill}function bw(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();if(!e)return null;e=e.replace(/^\/+/,"");let t=e.lastIndexOf(":");return t!==-1&&(e=e.slice(t+1).replace(/^\/+/,"")),e||null}var ww=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 Kp(r){if(!r.startsWith("mcp__"))return null;let e=r.split("__");if(e.length<3)return null;let t=e[1].toLowerCase();return!t.includes("claude-mem")&&!t.includes("claude_mem")&&!t.includes("mcp-search")&&!t.includes("mcp_search")&&!t.includes("cmem")?null:e.slice(2).join("__")}function Gp(r){if(!r)return!1;if(r.startsWith("memory_")||r==="mem_search"||r==="get_summaries")return!0;let e=Kp(r);return e!==null&&ww.has(e)}function zp(r){return r==="save_memory"||Kp(r)==="save_memory"}var qp=require("crypto");var Ti=new WeakMap,Yp=720*60*60*1e3,Jp=(...r)=>(0,qp.createHash)("sha256").update(r.join("\0")).digest("hex");function Tw(r){Ti.has(r)||(r.run("CREATE TABLE IF NOT EXISTS work_state_telemetry_receipts (key TEXT PRIMARY KEY, state TEXT, created_at_epoch INTEGER NOT NULL DEFAULT 0)"),r.query("PRAGMA table_info(work_state_telemetry_receipts)").all().some(n=>n.name==="created_at_epoch")||r.run("ALTER TABLE work_state_telemetry_receipts ADD COLUMN created_at_epoch INTEGER NOT NULL DEFAULT 0"),r.run("CREATE INDEX IF NOT EXISTS idx_work_state_telemetry_age ON work_state_telemetry_receipts(created_at_epoch)"),Ti.set(r,0));let e=Date.now();e-Ti.get(r)>=3600*1e3&&(r.query("DELETE FROM work_state_telemetry_receipts WHERE created_at_epoch < ?").run(e-Yp),Ti.set(r,e))}function Xp(r){return Bp()?(Tw(r),!0):!1}function Qp(r){return Jp(wr(r.platformSource),r.contentSessionId,r.agentId??"")}function Aw(r,e){let t=r.query("SELECT state FROM work_state_telemetry_receipts WHERE key = ?").get(`instruction:${Qp(e)}`);if(!t?.state)return null;try{let n=JSON.parse(t.state);return n&&["returned","disabled","excluded","missing","unknown"].includes(n.state)&&Number.isFinite(n.at)?n:null}catch{return null}}function Vp(r,e){let t=Aw(r,e),n=t&&Number.isFinite(e.enqueuedAtEpochMs)&&t.at<=e.enqueuedAtEpochMs?t.state:"unknown";return{platform:wr(e.platformSource),agent_role:e.agentRole??(vs(e.agentId,e.agentType)?"subagent":e.agentId||e.agentType?"main":"unknown"),instruction_state:n}}function Rw(r,e){return r.query("INSERT OR IGNORE INTO work_state_telemetry_receipts (key, created_at_epoch) VALUES (?, ?)").run(e,Date.now()).changes>0}function Zp(r){return typeof r=="number"&&Number.isFinite(r)&&r>=Date.now()-Yp}function sc(r,e){try{if(!Xp(r)||!Zp(e.enqueuedAtEpochMs))return!1;let t=r.query("SELECT state FROM work_state_telemetry_receipts WHERE key = ?").get(`privacy:${Qp(e)}`);if(!t?.state)return!1;let n=JSON.parse(t.state);return n.private===!1&&Number.isFinite(n.at)&&n.at<=e.enqueuedAtEpochMs}catch{return!1}}function vw(r){try{r()}catch{}}function ic(r,e,t,n,s){vw(()=>{if(!Xp(r)||!Zp(e.enqueuedAtEpochMs))return;if(!t){Ct.record("work_state_usage",null,{...Vp(r,e),unidentified_tool_event_count:1});return}if(!Rw(r,`tool:${Jp(e.contentSessionId,t)}`))return;let i=ls(n);Ct.record("work_state_usage",null,{...Vp(r,e),captured_tool_count:1,...i==="native_todo"?{native_todo_count:1}:i?{[`captured_${i}_count`]:1,[`captured_${i}_${Bo(i,s)}_count`]:1}:{}})})}var eg=null,Mw=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),tg=new Map;function Ow(r){let e=tg.get(r);if(e!==void 0)return e;let t=null;try{t=new RegExp(r)}catch(n){f.warn("INGEST","Invalid CLAUDE_MEM_SKIP_BASH_PATTERNS regex \u2014 ignoring",{pattern:r,error:n instanceof Error?n.message:String(n)})}return tg.set(r,t),t}function Cw(r,e){if(!e||typeof e!="object")return"";let t=e,n=r==="Bash"||r==="PowerShell"?t.command:r==="exec_command"?t.cmd:void 0;return typeof n=="string"?n:""}function Iw(){if(!eg)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return eg}async function rg(r,e={}){if(Gp(r.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};let{sessionManager:t,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:i}=Iw(),o=V(r.platformSource),a=typeof r.cwd=="string"?r.cwd:"",c=a.trim()?mt(a):null,l=c?.primary||"unknown",u=H.loadFromFile(ne);if(a&&Kn(a,u.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};let d=ls(r.toolName),g={...r,platformSource:r.telemetryPlatformSource??r.platformSource,enqueuedAtEpochMs:r.telemetryToolEpochMs??r.enqueuedAtEpochMs};if(d&&!Jo(r.agentId,r.agentType,u).skip)try{let S=n.getSessionStore(),T=S.findSessionDbIdByContentSessionId(r.contentSessionId,o),b=S.getPromptNumberFromUserPrompts(r.contentSessionId,T??void 0,r.enqueuedAtEpochMs);(T===null?null:S.getUserPrompt(r.contentSessionId,b,T))?.trim()&&sc(S.db,g)&&ic(S.db,g,r.toolUseId,r.toolName,r.toolResponse)}catch{}if(As(r.toolName,u.CLAUDE_MEM_SKIP_TOOLS)){if(r.toolName==="Skill"){let{skill_id:S,skill_source:T}=Hp(jp(r.toolName,r.toolInput));Ot("skill_invoked",{skill_id:S,skill_source:T,skill_trigger:"tool",ide:o})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(o==="kimi"&&Mw.has(r.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let p=u.CLAUDE_MEM_SKIP_BASH_PATTERNS.trim(),m=p?Cw(r.toolName,r.toolInput):"";if(m){let S=Ow(p);if(S&&S.test(m))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let h=Jo(r.agentId,r.agentType,u);if(h.skip)return{ok:!0,status:"skipped",reason:h.reason};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let S=r.toolInput,T=S.file_path||S.notebook_path;if(T&&T.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let E=n.getSessionStore(),y,w;try{y=E.createSDKSession(r.contentSessionId,l,"",void 0,o),a&&E.setSessionCwd(y,a,c?.keySource),w=E.getPromptNumberFromUserPrompts(r.contentSessionId,y,r.enqueuedAtEpochMs)}catch(S){let T=S instanceof Error?S.message:String(S);return f.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},S instanceof Error?S:new Error(T)),{ok:!1,reason:T,status:500}}let R=Ms.checkUserPromptPrivacy(E,r.contentSessionId,w,"observation",y,{tool_name:r.toolName});if(!R.allow)return{ok:!0,status:"skipped",reason:"private"};!d&&R.prompt.trim()&&sc(E.db,g)&&ic(E.db,g,r.toolUseId,r.toolName,r.toolResponse);let P=r.toolInput!==void 0?ps(JSON.stringify(r.toolInput)):"{}",O=r.toolResponse!==void 0?ps(JSON.stringify(r.toolResponse)):"{}";if(r.toolUseId)try{E.upsertToolUse({toolUseId:r.toolUseId,contentSessionId:r.contentSessionId,sessionDbId:y,project:l,platformSource:o,toolName:r.toolName,toolInput:P,toolResponse:O,cwd:a||null,promptNumber:w,agentType:typeof r.agentType=="string"?r.agentType:null,agentId:typeof r.agentId=="string"?r.agentId:null,orGenerationId:typeof r.orGenerationId=="string"?r.orGenerationId:null,orSessionId:typeof r.orSessionId=="string"?r.orSessionId:null})}catch(S){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:y,toolName:r.toolName,toolUseId:r.toolUseId},S instanceof Error?S:new Error(String(S)))}return zp(r.toolName)?{ok:!0,status:"skipped",reason:"explicit_memory_write"}:(t.queueObservation(y,{tool_name:r.toolName,tool_input:P,tool_response:O,prompt_number:w,cwd:a||(f.error("INGEST","Missing cwd when ingesting observation",{sessionId:y,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0},r.enqueuedAtEpochMs),e.markHandedOff?.(),await i?.(y,"observation"),s.broadcastObservationQueued(y),{ok:!0,sessionDbId:y})}var Pw=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function kw(r){let e=typeof r.agentId=="string"?r.agentId.trim():"";return e&&e!=="*"?e:r.path.match(Pw)?.[1]}var gn=class extends Error{constructor(e,t){super(`session init failed for transcript session ${e}: ${t instanceof Error?t.message:String(t)}`),this.name="TranscriptAnchorError",this.cause=t}},mn=class extends Error{constructor(e,t){super(`observation not accepted for transcript session ${e}: ${t instanceof Error?t.message:String(t)}`),this.name="TranscriptObservationError",this.cause=t}},It=class extends Error{constructor(e,t){super(`transcript event not persisted for session ${e}: ${t instanceof Error?t.message:String(t)}`),this.name="TranscriptSpoolError",this.cause=t}},xw=4096,Dw=64,Ai=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 t of this.sessionKeysOf(e)){let n=this.sessions.get(t);n&&n.cwd===e.cwd&&(n.cwd=void 0)}this.retireFileContext(e),e.cwd=void 0,e.sessionId=void 0}retireFileContext(e){for(let t of this.sessionKeysOf(e)){let n=this.sessions.get(t)?.pendingTools;for(let[s,i]of n??[])this.pendingToolOwners.get(i)===e&&n.delete(s)}this.fileContexts.delete(e),this.fileSessionKeys.delete(e),e.pendingTools={}}sessionKeysOf(e){return new Set([...Object.keys(e.pendingTools??{}),...this.fileSessionKeys.get(e)??[]])}async processEntry(e,t,n,s,i){i&&this.registerFileContext(i);for(let o of n.events)kr(e,o.match,n)&&await this.handleEvent(e,t,n,o,s??void 0,i)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),s=this.sessions.get(n);return s||(s={sessionId:t,platformSource:V(e.name),...this.subagentSessionKeys.has(n)?{isSubagent:!0}:{}},this.sessions.set(n,s)),s}rememberSubagentSession(e){if(this.subagentSessionKeys.delete(e),this.subagentSessionKeys.add(e),this.subagentSessionKeys.size>xw){let t=this.subagentSessionKeys.values().next().value;t!==void 0&&this.subagentSessionKeys.delete(t)}}async primeSessionContext(e,t,n,s,i){for(let o of n.events)o.action!=="session_context"||!kr(e,o.match,n)||await this.handleEvent(e,t,n,o,s??void 0,i)}resolveSessionId(e,t,n,s,i){let o={watch:t,schema:n},a=s.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=jt(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):i&&i.trim()?i:null}resolveCwd(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=jt(a,e,o);return typeof c=="string"&&c.trim()?c:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=jt(a,e,o);return typeof c=="string"&&c.trim()?c:t.project?t.project:i.cwd?mt(i.cwd).primary:i.project}async handleEvent(e,t,n,s,i,o){let a=this.resolveSessionId(e,t,n,s,o?.sessionId??i);if(!a){f.debug("TRANSCRIPT","Skipping event without sessionId",{event:s.name,watch:t.name});return}o&&(o.sessionId=a);let c=this.getOrCreateSession(t,a),l=this.getSessionKey(t,a);if(o){let p=this.fileSessionKeys.get(o)??new Set;p.add(l),this.fileSessionKeys.set(o,p)}if(o?.pendingTools?.[l]){c.pendingTools??=new Map;for(let[p,m]of Object.entries(o.pendingTools[l]))this.pendingToolOwners.set(m,o),c.pendingTools.has(p)||c.pendingTools.set(p,m)}!c.cwd&&o?.cwd&&(c.cwd=o.cwd);let u=this.resolveCwd(e,t,n,s,c);u&&(c.cwd=u);let d=this.resolveProject(e,t,n,s,c);if(d&&(c.project=d),t.subagentSource&&!c.isSubagent){let p=Pr(e,t.subagentSource.path);p!=null&&(c.isSubagent=!0,this.rememberSubagentSession(this.getSessionKey(t,a)))}if(t.subagentOnly&&!c.isSubagent&&s.action!=="session_context"&&s.action!=="session_end")return;let g=bd(s.fields,e,{watch:t,schema:n,session:c});s.action==="session_context"&&this.applySessionContext(c,g),o&&c.cwd&&(o.cwd=c.cwd);try{switch(s.action){case"session_context":break;case"session_init":await this.handleSessionInit(c,g),t.context?.updateOn?.includes("session_start")&&await this.updateContext(c,t);break;case"user_message":{let p=this.resolveMessageText(g.message)??this.resolveMessageText(g.prompt);p&&await this.anchorUserPrompt(c,p);break}case"assistant_message":c.lastAssistantMessage=this.resolveMessageText(g.message)??c.lastAssistantMessage;break;case"tool_use":await this.handleToolUse(c,t,g,o);break;case"tool_result":await this.handleToolResult(c,t,g,o);break;case"observation":await this.sendObservation(c,t,g);break;case"file_edit":await this.sendFileEdit(c,g);break;case"session_end":await this.handleSessionEnd(c,t);break;default:break}}finally{o&&this.snapshotPendingTools(o,c,l,s.action==="session_end")}}snapshotPendingTools(e,t,n,s){let i=s?{}:{...e.pendingTools?.[n]};for(let[a,c]of t.pendingTools??[])this.pendingToolOwners.get(c)===e&&(i[a]=c);e.pendingTools={...e.pendingTools,[n]:i},Object.keys(i).length===0&&delete e.pendingTools[n];let o=Object.entries(e.pendingTools).flatMap(([a,c])=>Object.keys(c).map(l=>[a,l]));for(let[a,c]of o.slice(0,Math.max(0,o.length-Dw))){let l=e.pendingTools[a],u=l[c];delete l[c],Object.keys(l).length===0&&delete e.pendingTools[a];let d=this.sessions.get(a)?.pendingTools;d?.get(c)===u&&d.delete(c)}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,s=typeof t.project=="string"?t.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 t=[];for(let n of e)n&&typeof n=="object"&&typeof n.text=="string"&&t.push(n.text);return t.length>0?t.join(`
35
- `):void 0}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"";await this.anchorUserPrompt(e,n)}async anchorUserPrompt(e,t){t&&(e.lastUserMessage=t);let n=e.cwd;if(!n){this.skipWithoutCwd(e,"user prompt");return}try{await rd({sessionId:e.sessionId,cwd:n,prompt:t,platform:e.platformSource})}catch(s){throw new gn(e.sessionId,s)}}skipWithoutCwd(e,t){f.debug("TRANSCRIPT",`Skipping a ${t}: the session has no known working directory yet`,{sessionId:e.sessionId})}async handleToolUse(e,t,n,s){let i=typeof n.toolId=="string"?n.toolId:void 0,o=typeof n.toolName=="string"?n.toolName:void 0,a=this.maybeParseJson(n.toolInput),c=this.maybeParseJson(n.toolResponse);if(o==="apply_patch"&&typeof a=="string"){let l=this.parseApplyPatchFiles(a);for(let u of l)await this.sendFileEdit(e,{filePath:u,edits:[{type:"apply_patch",patch:a}]})}if(o&&c!==void 0)await this.sendObservation(e,t,{toolName:o,toolInput:a,toolResponse:c,toolUseId:i});else if(o&&i){e.pendingTools||(e.pendingTools=new Map);let l={toolName:o,toolInput:a};s&&this.pendingToolOwners.set(l,s),e.pendingTools.set(i,l)}}async handleToolResult(e,t,n,s){let i=typeof n.toolId=="string"?n.toolId:void 0,o=typeof n.toolName=="string"?n.toolName:void 0,a=this.maybeParseJson(n.toolResponse),c=this.maybeParseJson(n.toolInput),l=s?.pendingTools?.[this.getSessionKey(t,e.sessionId)],u=i?e.pendingTools?.get(i):void 0,d=s,g=s?(i?l?.[i]:void 0)??(u&&this.pendingToolOwners.get(u)===s?u:void 0):u;if(!g&&s&&i){let p=Array.from(this.fileContexts).flatMap(m=>{let h=m.pendingTools?.[this.getSessionKey(t,e.sessionId)]?.[i];return h&&m.isCurrent?.()!==!1?[{context:m,tool:h}]:[]});p.length===1&&(d=p[0].context,g=p[0].tool)}if(g&&(o||(o=g.toolName),c===void 0&&(c=g.toolInput)),o){if(await this.sendObservation(e,t,{toolName:o,toolInput:c,toolResponse:a,toolUseId:i}),i){e.pendingTools&&e.pendingTools.get(i)===g&&e.pendingTools.delete(i);let p=d?.pendingTools?.[this.getSessionKey(t,e.sessionId)];p&&delete p[i]}}else f.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:i})}async sendObservation(e,t,n){let s=typeof n.toolName=="string"?n.toolName:void 0;if(!s)return;if(!e.cwd){this.skipWithoutCwd(e,"observation");return}let i={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:kw(t)};if(this.observationTransport==="spool"){try{Or("observation",i)}catch(a){throw new It(e.sessionId,a)}return}let o=!1;try{let a=await rg(i,{markHandedOff:()=>{o=!0}});if(!a.ok)throw new Error(a.reason)}catch(a){if(o){f.warn("TRANSCRIPT","Observation accepted before generator kick failed",{sessionId:e.sessionId},a instanceof Error?a:void 0);return}throw new mn(e.sessionId,a)}}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;if(n){if(!e.cwd){this.skipWithoutCwd(e,"file edit");return}try{await md.execute({sessionId:e.sessionId,cwd:e.cwd,filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}catch(s){throw new It(e.sessionId,s)}}}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return f.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
36
- `);for(let s of n){let i=s.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let o=i.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&t.push(o)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){(!t.subagentOnly||e.isSubagent)&&(await this.queueSummary(e),await this.updateContext(e,t)),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(this.observationTransport==="spool"){try{Or("summarize",{contentSessionId:e.sessionId,platformSource:e.platformSource,lastAssistantMessage:e.lastAssistantMessage??"",...e.cwd?{cwd:e.cwd}:{}})}catch(i){throw new It(e.sessionId,i)}return}if(!await is())return;let n=e.lastAssistantMessage??"",s=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource,...e.cwd?{cwd:e.cwd}:{}});try{await Fe("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:s})}catch(i){f.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||xc(t)||!await is())return;let s=e.cwd??t.workspace;if(!s)return;let o=mt(s).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=ie(t.context.path??`${s}/AGENTS.md`),l=pn.default.resolve(c),u=[pn.default.resolve(s),pn.default.resolve(U)];if(!u.some(m=>l.startsWith(m+pn.default.sep)||l===m)){f.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:l,allowedRoots:u});return}let g;try{g=await Fe(a)}catch(m){f.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:m instanceof Error?m.message:String(m)});return}if(!g.ok)return;let p=(await g.text()).trim();p&&(Ed(c,p),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:t.name}))}};var ng=me(require("node:zlib"),1),ir=require("node:fs");M();function sg(){let r=ng.zstdDecompressSync;return typeof r=="function"?r:void 0}function ig(){return sg()!==void 0}var Lw=4247762216,Nw=64*1024;function Ri(r,e,t,n=Number.POSITIVE_INFINITY){let s=(0,ir.openSync)(r,"r");try{let i=Buffer.alloc(0),o=0,a=(u,d)=>{if(u+d>t)return null;if(u<o||u+d>o+i.length){let g=Math.min(Math.max(d,Nw),t-u),p=Buffer.alloc(g);if(i=p.subarray(0,(0,ir.readSync)(s,p,0,g,u)),o=u,i.length<d)return null}return i.subarray(u-o,u-o+d)},c=[],l=e;for(;l<t&&(c.length===0||l-e<n);){let u=l,d=a(l,4);if(!d)return{frames:c,tornStart:u};if(d.readUInt32LE(0)!==Lw)throw new Error(`invalid Zstandard frame magic at byte ${l}`);l+=4;let g=a(l,1);if(!g)return{frames:c,tornStart:u};let p=g.readUInt8(0);if(l+=1,(p&8)!==0)throw new Error(`reserved Zstandard frame-header bit at byte ${l-1}`);let m=p>>>6,h=(p&32)!==0,_=(p&4)!==0,E=p&3,y=E===3?4:E,w=m===0?h?1:0:1<<m,R=(h?0:1)+y+w;if(l+R>t)return{frames:c,tornStart:u};for(l+=R;;){let P=a(l,3);if(!P)return{frames:c,tornStart:u};let O=P.readUIntLE(0,3);l+=3;let S=(O&1)!==0,T=O>>>1&3,b=O>>>3;if(T===3)throw new Error(`reserved Zstandard block type at byte ${l-3}`);let C=T===1?1:b;if(l+C>t)return{frames:c,tornStart:u};if(l+=C,S)break}if(_){if(l+4>t)return{frames:c,tornStart:u};l+=4}c.push({start:u,end:l})}return{frames:c,tornStart:null}}finally{(0,ir.closeSync)(s)}}function oc(r,e){try{let t=sg();if(!t)throw new Error("this runtime cannot decode Zstandard (zlib.zstdDecompressSync is missing)");return t(r.subarray(e.start,e.end))}catch(t){throw f.warn("TRANSCRIPT","Failed to decompress Zstandard frame",{start:e.start,end:e.end,error:t instanceof Error?t.message:String(t)}),t}}function og(r,e){return oc(r,e).toString("utf8")}var ag=2e3,Fw=1e3,Uw=256*1024,cg=4*1024*1024,$w=16*1024*1024,Bw=100,lg=100;function hn(){return new Promise(r=>setImmediate(r))}var vi=".jsonl.zstd";async function Ww(r,e){try{let t=0;for(;t<e;){let n=Ri(r,t,e,$w);if(n.tornStart!==null)return n.tornStart;if(n.frames.length===0)break;t=n.frames[n.frames.length-1].end,await hn()}return t}catch{return e}}var ug=1024*1024;async function pg(r,e,t){let n;if(e){let{frames:i}=Ri(r,0,Math.min(t,ug),1);if(i.length===0)return null;n=og(await Oi(r,0,i[0].end),i[0])}else n=(await Oi(r,0,Math.min(t,ug))).toString("utf8");let s=n.indexOf(`
37
- `);return s<0?null:n.slice(0,s)}async function Hw(r,e,t){try{let n=await pg(r,e,t);if(n===null)return null;let s=JSON.parse(n);for(let i of["timestamp","time","createdAt"]){let o=s?.[i],a=typeof o=="number"?o<1e12?o*1e3:o:typeof o=="string"?Date.parse(o):Number.NaN;if(Number.isFinite(a)&&a>0)return a}return null}catch{return null}}function Mi(r){return`${r.dev}:${r.ino}`}function jw(r){try{return(0,B.statSync)(r),!1}catch(e){let t=e.code;return t==="ENOENT"||t==="ENOTDIR"}}var Kw=4096;function cc(r,e,t){let n;try{if(n=(0,B.openSync)(r,"r"),Mi((0,B.fstatSync)(n))!==t)return null;let s=Math.max(0,e-Kw),i=Buffer.alloc(e-s);return(0,B.readSync)(n,i,0,i.length,s)<i.length?null:(0,dg.createHash)("sha256").update(i).digest("hex")}catch(s){return f.debug("TRANSCRIPT","Could not fingerprint a transcript checkpoint",{file:r},s instanceof Error?s:void 0),null}finally{n!==void 0&&(0,B.closeSync)(n)}}function gg(r,e,t,n,s){return t<n?!1:s===void 0?!0:cc(r,n,e)===s}async function Oi(r,e,t){let n=await(0,fg.open)(r,"r");try{let s=Buffer.alloc(t),{bytesRead:i}=await n.read(s,0,t,e);return s.subarray(0,i)}finally{await n.close()}}var ac=class{constructor(e,t,n,s,i="",o=0,a,c,l,u){this.filePath=e;this.onLine=n;this.onOffset=s;this.onReset=l;this.fileIdentity=a,this.checkpointFingerprint=c,this.isZstd=e.endsWith(vi),this.zstdPartialBytes=this.isZstd&&u?Buffer.from(u,"base64"):void 0,this.tailState={offset:t,readOffset:t,partial:this.isZstd?i:""},this.frameLinesDone=this.isZstd?o:0}filePath;onLine;onOffset;onReset;watcher=null;tailState;readTask=null;readPending=!1;closed=!1;isZstd;pendingRecord=Buffer.alloc(0);frameLinesDone;zstdPartialBytes;fileIdentity;checkpointFingerprint;start(){this.requestRead();try{this.watcher=(0,B.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})}}async drainReads(){do this.readPending=!1,await this.readNewData().catch(()=>{}),this.readPending&&await hn();while(this.readPending&&!this.closed)}async readNewData(){if(!(0,B.existsSync)(this.filePath))return;let e=0,t;try{let o=(0,B.statSync)(this.filePath);e=o.size,t=Mi(o)}catch(o){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}let n=t!==this.fileIdentity,s=!1;n&&this.fileIdentity!==void 0&&(gg(this.filePath,t,e,this.tailState.offset,this.checkpointFingerprint)?(this.tailState.readOffset=this.tailState.offset,this.pendingRecord=Buffer.alloc(0)):s=!0),this.fileIdentity=t;let i=s||e<this.tailState.readOffset;if(i&&(this.onReset?.(),this.tailState.offset=0,this.tailState.readOffset=0,this.tailState.partial="",this.zstdPartialBytes=void 0,this.pendingRecord=Buffer.alloc(0),this.frameLinesDone=0),e===this.tailState.readOffset){(n||i)&&this.checkpoint(this.tailState.offset,this.tailState.partial);return}this.isZstd?await this.readNewZstdFrames(e):await this.readNewJsonl(e)}checkpoint(e,t="",n=this.zstdPartialBytes){this.zstdPartialBytes=n,this.tailState.offset=e,this.tailState.partial=t,this.checkpointFingerprint=this.fileIdentity===void 0?void 0:cc(this.filePath,e,this.fileIdentity)??void 0,this.onOffset(e,t,this.frameLinesDone,this.fileIdentity,this.checkpointFingerprint,this.zstdPartialBytes?.toString("base64"))}async readNewJsonl(e){let t=this.tailState.readOffset,n;try{n=await Oi(this.filePath,t,Math.min(e-t,cg))}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=t+n.length;let s=this.pendingRecord.length>0?Buffer.concat([this.pendingRecord,n]):n,i=this.tailState.offset,o=0,a=0;for(let c=s.indexOf(10);c!==-1;c=s.indexOf(10,o)){if(this.closed){this.checkpoint(i+o);return}let l=s.toString("utf8",o,c).trim();if(l)try{await this.onLine(l)}catch{this.pendingRecord=Buffer.alloc(0),this.tailState.readOffset=i+o,this.checkpoint(i+o);return}o=c+1,this.tailState.offset=i+o,l&&++a%lg===0&&(this.checkpoint(this.tailState.offset),await hn())}this.pendingRecord=Buffer.from(s.subarray(o)),this.checkpoint(i+o),this.tailState.readOffset<e&&(this.readPending=!0)}async readNewZstdFrames(e){let t=this.tailState.offset,n,s;try{if(n=Ri(this.filePath,t,e,cg),n.frames.length===0)return;let o=n.frames[n.frames.length-1].end;if(s=await Oi(this.filePath,t,o-t),s.length<o-t)return}catch(o){f.warn("TRANSCRIPT","Failed to read zstd transcript frames",{file:this.filePath,error:o instanceof Error?o.message:String(o)});return}let i=0;for(let o of n.frames){let a;try{a=oc(s,{start:o.start-t,end:o.end-t})}catch{this.checkpoint(this.tailState.offset,this.tailState.partial);return}let c=this.tailState.partial,l=this.zstdPartialBytes,u=Buffer.concat([l??Buffer.from(c,"utf8"),a]),d=[],g=0;for(let _=u.indexOf(10);_!==-1;_=u.indexOf(10,g))d.push(u.toString("utf8",g,_)),g=_+1;let p=u.subarray(g),m=p.toString("utf8"),h=Buffer.from(m,"utf8").equals(p)?void 0:Buffer.from(p);for(let _=this.frameLinesDone;_<d.length;_++){if(this.closed){this.frameLinesDone=_,this.checkpoint(o.start,c,l);return}let E=d[_].trim();if(E){try{await this.onLine(E)}catch{this.frameLinesDone=_,this.tailState.readOffset=o.start,this.checkpoint(o.start,c,l);return}++i%lg===0&&await hn()}}this.frameLinesDone=0,this.tailState.offset=o.end,this.tailState.readOffset=o.end,this.tailState.partial=h?"":m,this.zstdPartialBytes=h}this.checkpoint(this.tailState.offset,this.tailState.partial),n.tornStart===null&&this.tailState.offset<e&&(this.readPending=!0)}},Ci=class{constructor(e,t,n="in-process"){this.config=e;this.statePath=t;this.processor=new Ai(n),this.state=Bc(t)}config;statePath;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;missingTranscriptGraceMs=Fw;rootWatchers=[];rootWatchSettleTimers=new Set;startedAtMs=0;warnedZstdUnsupported=!1;startingTailers=new Set;stopped=!1;async start(){this.stopped=!1,this.startedAtMs=Date.now();for(let e of this.config.watches)await this.setupWatch(e);if(!this.stopped)for(let e of Object.keys(this.state.pendingTools??{}))this.tailers.has(e)||this.scheduleRetirementCheck(e)}stop(){this.stopped=!0;for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[];for(let e of this.rootWatchSettleTimers)clearTimeout(e);this.rootWatchSettleTimers.clear(),this.retirementTimer&&clearTimeout(this.retirementTimer),this.retirementTimer=null,this.retirementCandidates.clear()}async setupWatch(e){let t=this.resolveSchema(e);if(!t){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=ie(e.path),s=this.resolveWatchFiles(n);for(let o of s)this.getFileContext(o);let i={stateChanged:!1};for(let o of s)await this.addTailer(o,e,t,!1,i),await hn();i.stateChanged&&gr(this.statePath,this.state),this.watchTranscriptRoot(n,e,t)}watchTranscriptRoot(e,t,n,s=!1){let i=this.selectWatchRoot(e);if(!i){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:t.name,path:e});return}let{root:o,recursive:a}=i;try{let c=(0,B.watch)(o,{recursive:a,persistent:!0},(l,u)=>{a?this.handleRootWatchEvent(o,e,t,n,u):this.handleAncestorWatchEvent(c,o,e,t,n,u)});this.rootWatchers.push(c),(s||!a)&&this.settleRootWatch(c,o,a,e,t,n),f.info("TRANSCRIPT",a?"Watching transcript root recursively":"Transcript root does not exist yet; watching its closest existing directory",{watch:t.name,watchRoot:o})}catch(c){f.warn("TRANSCRIPT","Failed to start fs.watch on transcript root",{watch:t.name,watchRoot:o},c instanceof Error?c:void 0)}}handleRootWatchEvent(e,t,n,s,i){if(!i)return;let o=(0,z.resolve)(e,i).replace(/\\/g,"/"),a=this.tailers.get(o);if(a){if(!(0,B.existsSync)(o)){a.close(),this.tailers.delete(o),this.scheduleRetirementCheck(o);return}a.poke();return}this.touchesLiteralPrefix(o,t)&&this.addDiscoveredTailers(t,n,s)}handleAncestorWatchEvent(e,t,n,s,i,o){if(this.stopped||!this.rootWatchers.includes(e)||o&&!this.touchesLiteralPrefix((0,z.resolve)(t,o),n))return;let a=this.selectWatchRoot(n);a&&a.root===t&&!a.recursive||(e.close(),this.rootWatchers=this.rootWatchers.filter(c=>c!==e),this.watchTranscriptRoot(n,s,i,!0),this.addDiscoveredTailers(n,s,i))}settleRootWatch(e,t,n,s,i,o){let a=setTimeout(()=>{this.rootWatchSettleTimers.delete(a),!(this.stopped||!this.rootWatchers.includes(e))&&(n?this.addDiscoveredTailers(s,i,o):this.handleAncestorWatchEvent(e,t,s,i,o,null))},Bw);this.rootWatchSettleTimers.add(a)}getFileContext(e){let t=this.fileContexts.get(e);return t||(t={cwd:this.state.cwds?.[e],pendingTools:this.state.pendingTools?.[e],isCurrent:()=>this.isCheckpointedFile(e)},this.fileContexts.set(e,t)),this.processor.registerFileContext(t),t}isCheckpointedFile(e){try{let t=(0,B.statSync)(e);return Mi(t)===this.state.fileIdentities?.[e]&&t.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 t=!1;for(let n of e){if(this.tailers.has(n)||!jw(n))continue;let s=this.fileContexts.get(n);s&&this.processor.retireFileContext(s),this.fileContexts.delete(n),this.state.pendingTools?.[n]&&(delete this.state.pendingTools[n],t=!0)}t&&gr(this.statePath,this.state)}forgetReplacedTranscript(e,t){this.processor.resetFileContext(t),delete this.state.pendingTools?.[e],delete this.state.cwds?.[e]}addDiscoveredTailers(e,t,n){for(let s of this.resolveWatchFiles(e))this.tailers.has(s)||this.addTailer(s,t,n,!0).catch(i=>{f.debug("TRANSCRIPT","Failed to add transcript tailer",{file:s,watch:t.name},i instanceof Error?i:void 0)})}touchesLiteralPrefix(e,t){let n=e.replace(/\\/g,"/"),s=(0,z.resolve)(this.literalWatchPrefix(t)).replace(/\\/g,"/"),i=(o,a)=>o.startsWith(a.endsWith("/")?a:a+"/");return n===s||i(n,s)||i(s,n)}literalWatchPrefix(e){let t=e;if(this.hasGlob(e)){let n=e.split(/[/\\]/),s=[];for(let i of n){if(/[*?[\]{}()]/.test(i))break;s.push(i)}if(s.length===0||s.length===1&&s[0]==="")return"";t=s.join(z.sep)}return t}selectWatchRoot(e){let t=this.literalWatchPrefix(e);if(!t)return null;let n=(0,z.resolve)(t);try{return{root:(0,B.statSync)(n).isDirectory()?n:(0,z.resolve)(n,".."),recursive:!0}}catch{}for(let s=(0,z.resolve)(n,"..");(0,z.resolve)(s,"..")!==s;s=(0,z.resolve)(s,".."))try{if((0,B.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,B.existsSync)(e))try{return(0,B.statSync)(e).isDirectory()?[...this.scanGlob(this.normalizeGlobPattern((0,z.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,z.join)(e,"**",`*${vi}`)))]:[e]}catch(t){return f.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){try{return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0,dot:!0}))}catch(t){let n=t?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw t}}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n,s=!1,i){if(e=ie(e),!(this.tailers.has(e)||this.startingTailers.has(e))){this.startingTailers.add(e);try{await this.startTailer(e,t,n,s,i)}finally{this.startingTailers.delete(e)}}}async startTailer(e,t,n,s,i){let o=e.endsWith(vi);if(o&&!ig()){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),l=this.state.offsets[e],u=l??0,d=!1;if(l===void 0&&t.startAtEnd)try{let m=(0,B.statSync)(e);if(s&&m.mtimeMs>=this.startedAtMs-ag&&await this.startedAfterThisWatcher(e,o,m.size)||(u=o?await Ww(e,m.size):m.size),this.stopped)return;this.state.offsets[e]=u,d=!0}catch(m){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},m instanceof Error?m:void 0),u=0}try{let m=(0,B.statSync)(e),h=Mi(m),_=this.state.fileIdentities?.[e],E=l!==void 0&&_!==void 0&&!gg(e,h,m.size,l,this.state.checkpointFingerprints?.[e]);if(E&&(u=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)),E||h!==_){(this.state.fileIdentities??={})[e]=h;let y=cc(e,u,h);y!==null?(this.state.checkpointFingerprints??={})[e]=y: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?gr(this.statePath,this.state):i&&(i.stateChanged=!0));let g=u>0&&(!!n.sessionIdPath||!!t.subagentSource||!c.cwd),p=new ac(e,u,async m=>{try{g&&(g=!1,await this.primeFromFirstLine(e,u,t,n,a,c)),await this.handleLine(m,t,n,e,a,c)}finally{c.pendingTools&&((this.state.pendingTools??={})[e]=c.pendingTools),c.cwd&&c.cwd!==this.state.cwds?.[e]&&((this.state.cwds??={})[e]=c.cwd)}},(m,h,_,E,y,w)=>{E!==void 0&&((this.state.fileIdentities??={})[e]=E),y!==void 0?(this.state.checkpointFingerprints??={})[e]=y: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],gr(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]);p.start(),this.tailers.set(e,p),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async startedAfterThisWatcher(e,t,n){let s=await Hw(e,t,n);return s!==null?s>=this.startedAtMs-ag:n<=Uw}async primeFromFirstLine(e,t,n,s,i,o){try{let a=await pg(e,e.endsWith(vi),t);if(a===null)return;await this.processor.primeSessionContext(JSON.parse(a),n,s,i,o)}catch(a){f.debug("TRANSCRIPT","Could not read the first line of a resumed transcript",{watch:n.name,file:(0,z.basename)(e)},a instanceof Error?a:void 0)}}async handleLine(e,t,n,s,i,o){try{let a=JSON.parse(e);await this.processor.processEntry(a,t,n,i??void 0,o)}catch(a){if(a instanceof gn||a instanceof mn||a instanceof It)throw f.warn("TRANSCRIPT","Transcript event not accepted; it is retried from its own line",{watch:t.name,file:(0,z.basename)(s),error:a.message}),a;a instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,z.basename)(s)},a):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,z.basename)(s),error:String(a)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function lc(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}function mg(r){(0,hg.existsSync)(ie(r))||(Wi(r),console.log(`Created sample config: ${ie(r)}`))}async function _g(r,e){switch(r){case"init":{let t=lc(e,"--config")??Dt;return Wi(t),console.log(`Created sample config: ${ie(t)}`),0}case"watch":{let t=lc(e,"--config")??Dt;mg(t);let n=H.loadFromFile(ne),{config:s,scoped:i,removed:o}=Dc(Bi(t),n);if(i>0&&console.log(`Scoped ${i} Codex transcript watch(es) to subagent sessions (CLAUDE_MEM_CODEX_SUBAGENT_INGESTION=true); native hooks capture top-level sessions.`),o>0&&console.log(`Skipped ${o} Codex transcript watch(es): native hooks capture top-level Codex sessions, and subagent capture is opt-in (CLAUDE_MEM_CODEX_SUBAGENT_INGESTION=true).`),s.watches.length===0)return console.log(`No active transcript watches in ${ie(t)}; nothing to watch.`),1;let a=ie(s.stateFile??Rn),c=new Ci(s,a,"spool");await c.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let l=()=>{c.stop(),process.exit(0)};return process.on("SIGINT",l),process.on("SIGTERM",l),await new Promise(()=>{})}case"validate":{let t=lc(e,"--config")??Dt;return mg(t),Bi(t),console.log(`Config OK: ${ie(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Gw=process.argv[2],zw=process.argv.slice(3);_g(Gw,zw).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
32
+ at ${t.filename}:${n}:${s}`}};var PS=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,$r=class{match(e){return typeof e=="string"}coerce(e,t){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,s=e.match(PS);return s&&(t=s[1],n=s[2]),[t,n]}};var hf=["fatal","error","warning","log","info","debug"];function Hs(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let s=t.slice(0,n).join(", ");if(!(s.length>e))return n===t.length||s.length<=e?s:`${s.slice(0,e)}...`}return""}var Br=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Vt(e))return e.constructor.name;let t="name"in e?e.name:void 0;return ee(t)&&!Xo(t)?t:"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 t=this.getObjectClassName(e),n=Hs(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return ee(e)&&!Xo(e)&&hf.indexOf(e)>=0}getStack(e){try{return ee(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ee(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(nt(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var ha=class{match(e){return Vt(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Hs(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Wr=class{match(e){return Cs(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var _a=class{match(e){return yt(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Vt(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return Cs(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.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 Ea=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var Hr={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kS=new Set([Hr.MESSAGE,Hr.TIMESTAMP]),js={enabled:!0,max_bytes:32768};function Sa(r){return r?{enabled:r.enabled??js.enabled,max_bytes:DS(r.max_bytes,js.max_bytes)}:{...js}}function xS(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,s)=>kS.has(s)?(e.push(s),n):(n[s]=r[s],n),{}),droppedKeys:e}}var ya=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Sa(e)}setConfig(e){this._config=Sa(e),this._trimToMaxBytes()}add(e){let t=LS(e);if(!t)return;let n=_f(t.json);n>this._config.max_bytes||(this._entries.push({step:t.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 DS(r,e){if(!zt(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function LS(r){let e;try{e=rt(r)}catch{return}try{let t=JSON.parse(e);if(!xr(t))return;let n=t,s=n[Hr.MESSAGE],i=n[Hr.TIMESTAMP];return!ee(s)||s.trim().length===0||!ee(i)&&!zt(i)?void 0:{step:n,json:e}}catch{return}}function _f(r){if("u">typeof TextEncoder)return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}function NS(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let r=globalThis._posthogReleaseId;return typeof r=="string"&&r.length>0?r:void 0}var ba=r=>{if("flags"in r){let e=Ef(r.flags),t=Sf(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([s,i])=>[s,Qt(i)])),n=Object.fromEntries(Object.entries(e).map(([s,i])=>[s,FS(s,i,t[s])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function FS(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var Ef=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,jr(t)]).filter(([,e])=>e!==void 0)),Sf=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?Qt(n):void 0]}))},jr=r=>r===void 0?void 0:r.variant??r.enabled,Qt=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var yf=["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"],US=["$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",...yf,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Kr=(r,e=[])=>{let t={},n=s=>{r[s]!==void 0&&(t[s]=r[s])};return US.forEach(n),e.forEach(n),t};var Ks=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};function wa(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var BS="NativeGzipValidationError",WS=31,HS=139,jS=8,KS=r=>r.length>=2&&r[0]===WS&&r[1]===HS;var Gr,GS=()=>{if(Gr)return Gr;Gr=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;Gr[r]=e>>>0}return Gr},zS=r=>{let e=GS(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},Gs=r=>{throw Jt(BS,`Native gzip produced invalid output: ${r}`)},VS=async(r,e)=>{r.size<18&&Gs("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!KS(t)||t[2]!==jS)&&Gs("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==zS(e)&&Gs("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&Gs("invalid-size")};async function zr(r,e=!0,t){try{let n=new TextEncoder().encode(r),s=new globalThis.CompressionStream("gzip"),i=s.writable.getWriter(),o=i.write(n).then(()=>i.close()).catch(async l=>{try{await i.abort(l)}catch{}throw l}),a=new Response(s.readable).blob(),[c]=await Promise.all([a,o]);return await VS(c,n),c}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var ye=class extends Error{constructor(e,t,n,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=n,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return oa(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=Jt("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=ce(()=>{this._bodyReadTimedOut=!0;let i=Jt("AbortError","Response body read timed out");s(i),this.cancelResponseBody(i)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(n){t=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([t,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{}})()}},qe=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var qS=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function bf(r){if(r instanceof ye){let e="";try{e=await r.text}catch{r.bodyReadTimedOut&&(e="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function YS(r){return typeof r=="object"&&(r instanceof ye||Rf(r))}function Rf(r){return r instanceof qe}function JS(r){if(r instanceof ye)return r.status===502||r.status===504;if(!(r instanceof qe))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var wf=10485760;function Tf(r){try{return typeof r!="string"?r instanceof Uint8Array?r.byteLength:r.size:"u">typeof Buffer?Buffer.byteLength(r,Jd):new TextEncoder().encode(r).length}catch{return 0}}function Zt(r){return typeof r=="object"&&r instanceof ye&&r.status===413}function zs(r){return r instanceof ye?r.status===408||r.status===429||r.status>=500:Rf(r)}function Af(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ta="default",Vr=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Fr([new Ur,new Br,new $r,new Wr],pa())}getEvaluationRuntime(){}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ds,this._events=new Ks,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof t.host=="string"?t.host.trim():"",i=!n;this._logger=Ld("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Xd(s||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:zs},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!wa()||(t?.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(de.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(de.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(de.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,s)=>this._logger.info(n,s));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n=this.mergeCommonEventProperties(t);return qS(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Kr(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,t,n){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",s,n)})}async identifyStatelessImmediate(e,t,n){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",s,n)}captureStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",i,s)})}async captureStatelessImmediate(e,t,n,s){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",i,s)}aliasStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",i,s)})}async aliasStatelessImmediate(e,t,n,s){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,s)}groupIdentifyStateless(e,t,n,s,i,o){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});this.enqueue("capture",a,s)})}async groupIdentifyStatelessImmediate(e,t,n,s,i,o){let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});await this.sendImmediate("capture",a,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,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,t={},n={},s={},i={},o=!1){await this._initPromise;let a=o?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:s,...i};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,d,{type:"required",consume:g=>g.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:JS},this.featureFlagsRequestTimeoutMs).then(g=>({success:!0,response:ba(g)})).catch(g=>(this._events.emit("error",g),{success:!1,error:this.categorizeRequestError(g)}))}categorizeRequestError(e){if(e instanceof ye)return{type:"api_error",statusCode:e.status};if(e instanceof qe){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,s,i,o);if(a===void 0)return{response:void 0,requestId:void 0};let c=jr(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,s,i,o,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,s,i,o,[e]);if(!a)return;let c=a[e];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(e,t={},n={},s={},i,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)).payloads}async getFeatureFlagsStateless(e,t={},n={},s={},i,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,s,i,o);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};o&&(a.flag_keys_to_evaluate=o);let c=await this.getFlags(e,t,n,s,a);if(!c.success)return;let l=c.response;return l.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"),l.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:l?.requestId,quotaLimited:l.quotaLimited}):l}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}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,t,{type:"required",consume:i=>{if(i.status!==200||!i.json){let o=`Surveys API could not be loaded: ${i.status}`,a=new Error(o);return this._logger.error(a),this._events.emit("error",new Error(o)),Promise.resolve(void 0)}return i.json()}}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return s&&this._logger.info("Surveys fetched from API: ",JSON.stringify(s)),s??[]}get props(){return this._props||(this._props=this.getPersistedProperty(de.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(de.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(de.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Ta}persistedQueueKeyForRoute(e){return de.Queue}getActiveQueueRoutes(){return[Ta]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let o=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(i)),a=this.getPersistedProperty(o)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:i}),this.setPersistedProperty(o,a),this._events.emit(e,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=ce(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i!==null){i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,s??this.getQueueRouteKey(i))}catch(o){this._events.emit("error",o)}}}normalizeMessage(e){let{type:t,library:n,library_version:s,...i}=e,o=Af(i.properties)?i.properties:void 0;return n!==void 0&&o?.$lib===void 0&&(o={...o||{},$lib:n}),s!==void 0&&o?.$lib_version===void 0&&(o={...o||{},$lib_version:s}),o&&(i.properties=o),i.uuid=wt(i.uuid,ae),i}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let n=t.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,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:aa(),uuid:wt(t?.uuid,ae)};return(t?.disableGeoip??this.disableGeoip)&&(Af(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 bf(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let n=t.filter(i=>!!i),s=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;s>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(o=>o.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,s])}).then(()=>Nr([t])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Nr([s]).then(()=>{this.flushPromises.delete(s),this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this.flushPromise===s&&(this.flushPromise=null)}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}compressPayload(e){return zr(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,n=Ta){let s={api_key:this.apiKey,batch:e.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:aa()};this.historicalMigration&&(s.historical_migration=!0);let i=rt(s),o=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(i),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await this.fetchWithRetry(o,c,{type:"successful-write"},t)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(s=>this.getRouteQueue(s).length>0))return;let t=[],n;for(let s of e)try{await this._flushRoute(s,t)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(n)||[];if(!s.length)return;let i=s.length,o=0;for(;s.length>0&&o<i;){let a=s.slice(0,this.maxBatchSize),c=a.map(d=>d.message===void 0?d.message:this.normalizeMessage(d.message)),l=async()=>{let d=this.getPersistedProperty(n)||[],g=[...a],p=d.filter(m=>{let h=m.message?.uuid,_=g.findIndex(E=>E===m||typeof h=="string"&&h.length>0&&E.message?.uuid===h);return _===-1?!0:(g.splice(_,1),!1)});this.setPersistedProperty(n,p),s=p,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:d=>Zt(d)?!1:zs(d)};try{await this.sendBatch(c,u,e)}catch(d){if(Zt(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 qe||await l(),this._events.emit("error",d),d}await l(),t.push(...c),o+=c.length}}async _sendOtlpBatch({path:e,auth:t,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let s;try{s=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let i=Tf(s);if(i>wf)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${i} bytes: the endpoint accepts at most ${wf}`)),{kind:"too-large",measuredLocally:!0};let o=t==="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,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(o,l,{type:"successful-write"},{retryCheck:u=>Zt(u)||u instanceof ye&&u.retryAfterMs!==void 0?!1:zs(u)}),{kind:"ok"}}catch(u){if(Zt(u))return{kind:"too-large"};if(zs(u)){let d=u instanceof ye?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...d!==void 0&&{retryAfterMs:d}}}return{kind:"fatal",error:u}}}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,t,n,s,i){let o=t.body?t.body:"",a=Tf(o),c={...this._retryOptions,...s},l=0;return await Qd(async()=>{l++;let u=new AbortController,d=i??this.requestTimeout,g=Date.now()+d,p,m=new Promise((w,R)=>{p=ce(()=>{let P=Jt("AbortError",`Request timed out after ${d}ms`);R(P),u.abort(P)},d)}),h,_=!1,E,y=()=>E??=(async()=>{try{await h?.body?.cancel()}catch{}})();try{let w;try{w=this.fetch(e,{signal:u.signal,...t})}catch(O){throw new qe(O)}w.then(O=>{u.signal.aborted&&!_&&Promise.resolve(O.body?.cancel()).catch(()=>{})}).catch(()=>{});try{h=await Promise.race([w,m]),_=!0}catch(O){throw new qe(O)}let R=t.mode==="no-cors",P=n.type==="successful-write"?300:400;if(!R&&(h.status<200||h.status>=P))throw new ye(h,a,g,u);if(n.type==="successful-write"){try{await Promise.race([y(),m])}catch{}return}try{return await Promise.race([n.consume(h),m])}catch(O){throw u.signal.aborted?new qe(O):O}}finally{clearTimeout(p),u.signal.aborted&&h&&y()}},{...c,retryCheck:u=>{let d=c.retryCheck(u);return d&&l<=c.retryCount&&u instanceof ye&&u.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;return this.clearFlushTimer(),this.disabled?void 0:st((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(o=>this.getRouteQueue(o).length>0);){let i=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===i){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!YS(s))throw s;await bf(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!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 ty=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var nP=new RegExp(ty.source,"i"),vf=/[a-z][a-z0-9+.-]{0,63}:\/\//i,sP=new RegExp(`^${vf.source}`,"i"),iP=new RegExp(vf.source,"gi");var ry=["is_not","is_set"],ny=1152921504606847e3,v=class r extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,r.prototype)}};function Aa(r){if(typeof r=="boolean")return!0;if(typeof r=="string"){let e=r.toLowerCase();return e==="true"||e==="false"}if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!Aa(e in r?r[e]:null))return!1;return!0}function Ra(r){if(typeof r=="boolean")return r;if(typeof r=="string")return r.toLowerCase()==="true";if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!Ra(e in r?r[e]:null))return!1;return!0}function qr(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t>=55296&&t<=56319){let n=r.charCodeAt(e+1);if(e+1>=r.length||n<56320||n>57343)throw new v("Cannot stringify an unpaired surrogate like the flags service");e++}else if(t>=56320&&t<=57343)throw new v("Cannot stringify an unpaired surrogate like the flags service")}}function qs(r,e=new Set){if(!(r===null||typeof r=="boolean")){if(typeof r=="string")return void qr(r);if(typeof r=="number"){if(!Number.isFinite(r))throw new v(`Cannot represent non-finite number ${r} like the flags service`);return}if(Array.isArray(r)){if(e.has(r))throw new v("Cannot represent a circular array during local evaluation");e.add(r);try{for(let t=0;t<r.length;t++)t in r&&qs(r[t],e)}finally{e.delete(r)}return}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new v("Cannot represent a non-JSON object like the flags service");if(e.has(r))throw new v("Cannot represent a circular object during local evaluation");e.add(r);try{for(let n of Object.keys(r))qr(n),qs(r[n],e)}finally{e.delete(r)}return}throw new v(`Cannot represent ${typeof r} like the flags service`)}}function sy(r,e){let t=0,n=0;for(;t<r.length&&n<e.length;){let s=r.charCodeAt(t),i=e.charCodeAt(n),o=s>=55296&&s<=56319,a=i>=55296&&i<=56319,c=o?r.charCodeAt(t+1):0,l=a?e.charCodeAt(n+1):0,u=o?(s-55296)*1024+c-56320+65536:s,d=a?(i-55296)*1024+l-56320+65536:i;if(u!==d)return u-d;t+=o?2:1,n+=a?2:1}return r.length-e.length}function va(r,e=new Set){if(r===null)return"null";if(typeof r=="string")return qr(r),JSON.stringify(r);if(typeof r=="boolean")return r?"true":"false";if(typeof r=="number"){if(!Number.isFinite(r))throw new v(`Cannot stringify non-finite number ${r} like the flags service`);if(Number.isInteger(r))throw new v(`Cannot distinguish integer ${r} from an integral JSON float during local evaluation`);return String(r)}if(Array.isArray(r)){if(e.has(r))throw new v("Cannot stringify a circular array during local evaluation");e.add(r);try{let t=[];for(let n=0;n<r.length;n++)t.push(n in r?va(r[n],e):"null");return`[${t.join(",")}]`}finally{e.delete(r)}}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new v("Cannot stringify a non-JSON object like the flags service");if(e.has(r))throw new v("Cannot stringify a circular object during local evaluation");e.add(r);try{let n=Object.keys(r);return n.forEach(qr),`{${n.sort(sy).map(s=>`${JSON.stringify(s)}:${va(r[s],e)}`).join(",")}}`}finally{e.delete(r)}}throw new v(`Cannot stringify ${typeof r} like the flags service`)}function Vs(r){return typeof r=="string"?(qr(r),r):va(r)}function Mf(r){try{return new RegExp(r),!0}catch{return!1}}function be(r){return String(r).replace(/[A-Z]/g,e=>e.toLowerCase())}function Cf(r,e,t){if(!/^\d+$/.test(r)||t==="strict"&&r.length>1&&r[0]==="0")throw new v(`Invalid semver: ${e}`);return parseInt(r,10)}function G(r,e="strict"){let n=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new v(`Invalid semver: ${r}`);let s=n.split("."),i=o=>o===void 0||o===""?0:Cf(o,r,e);return[i(s[0]),i(s[1]),i(s[2])]}function we(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function iy(r,e){let t=G(r,e);return{lower:[t[0],t[1],t[2]],upper:[t[0],t[1]+1,0]}}function oy(r,e){let[t,n,s]=G(r,e),i=[t,n,s],o;return o=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,s+1],{lower:i,upper:o}}function ay(r,e){let n=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new v(`Invalid wildcard semver: ${r}`);let s=n.split("."),i=c=>{if(e==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return Cf(c,r,e)}catch{}throw new v(`Invalid wildcard semver: ${r}`)},o=i(s[0]);if(s.length===1)return{lower:[o,0,0],upper:[o+1,0,0]};let a=i(s[1]);return{lower:[o,a,0],upper:[o,a+1,0]}}function Of(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new v(`${r} is in an invalid date format`)}throw new v(`The date provided ${r} must be a string, number, or date object`)}function Ma(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t||!t.groups)return null;let s=parseInt(t.groups.number);if(s>=1e4)return null;let i=t.groups.interval;if(i==="h")n.setUTCHours(n.getUTCHours()-s);else if(i==="d")n.setUTCDate(n.getUTCDate()-s);else if(i==="w")n.setUTCDate(n.getUTCDate()-7*s);else if(i==="m")n.setUTCMonth(n.getUTCMonth()-s);else{if(i!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-s)}return n}function Oa(r,e,t={}){let n=r.key,s=r.value,i=r.operator||"exact",o=t.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(e,n)){if(i==="is_not_set")return!1;if(i==="is_set")return!0}else throw new v(`Property ${n} not found in propertyValues`);let c=e[n];if(c===void 0)return t.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${i} operator`),i==="is_not";if(c===null&&!ry.includes(i)&&i!=="exact"&&i!=="is_not")return t.warnFunction?.(`Property ${n} cannot have a value of null with the ${i} operator`),!1;let l=(d,g)=>{if(t.propertyMatchingVersion!==2&&Aa(d)||Array.isArray(d)&&d.length===0)return qs(g),Ra(d)===Ra(g);if(t.propertyMatchingVersion===2&&typeof g=="number"&&Aa(d))return qs(g),!1;if(Array.isArray(d)){let p=Vs(g).toLowerCase();return d.some(m=>Vs(m).toLowerCase()===p)}return Vs(d).toLowerCase()===Vs(g).toLowerCase()},u=(d,g,p)=>{if(p==="gt")return d>g;if(p==="gte")return d>=g;if(p==="lt")return d<g;if(p==="lte")return d<=g;throw new Error(`Invalid operator: ${p}`)};switch(i){case"exact":return l(s,c);case"is_not":return!l(s,c);case"is_set":return!0;case"icontains":return be(c).includes(be(s));case"not_icontains":return!be(c).includes(be(s));case"starts_with":return be(c).startsWith(be(s));case"not_starts_with":return!be(c).startsWith(be(s));case"ends_with":return be(c).endsWith(be(s));case"not_ends_with":return!be(c).endsWith(be(s));case"regex":return Mf(String(s))&&String(c).match(String(s))!==null;case"not_regex":return Mf(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)),g=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(d)&&Number.isFinite(g)?u(g,d,i):u(String(c),String(s),i)}case"is_date_after":case"is_date_before":{if(typeof s=="boolean")throw new v("Date operations cannot be performed on boolean values");let d=Ma(String(s));d==null&&(d=Of(s));let g=Of(c);return i==="is_date_before"?g<d:g>d}case"semver_eq":return we(G(String(c),o),G(String(s),o))===0;case"semver_neq":return we(G(String(c),o),G(String(s),o))!==0;case"semver_gt":return we(G(String(c),o),G(String(s),o))>0;case"semver_gte":return we(G(String(c),o),G(String(s),o))>=0;case"semver_lt":return we(G(String(c),o),G(String(s),o))<0;case"semver_lte":return we(G(String(c),o),G(String(s),o))<=0;case"semver_tilde":{let d=G(String(c),o),{lower:g,upper:p}=iy(String(s),o);return we(d,g)>=0&&we(d,p)<0}case"semver_caret":{let d=G(String(c),o),{lower:g,upper:p}=oy(String(s),o);return we(d,g)>=0&&we(d,p)<0}case"semver_wildcard":{let d=G(String(c),o),{lower:g,upper:p}=ay(String(s),o);return we(d,g)>=0&&we(d,p)<0}default:throw new v(`Unknown operator: ${i}`)}}async function If(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function Yr(r,e,t="",n="."){let s=await If(`${r}${n}${e}${t}`);return parseInt(s.slice(0,15),16)/ny}async function Ca(r,e){if(r==null||r.id==null||r.exclusion_percentage==null)return;let t=Number(r.exclusion_percentage);if(!Number.isFinite(t))return;let n=Math.min(Math.max(t,0),100);if(!(n!==100&&await Yr("holdout",e,"","-")>n/100))return`holdout-${r.id}`}function Ys(r){let e=[],t=0;for(let n of r){let s=t+n.rollout_percentage/100;e.push({valueMin:t,valueMax:s,key:n.key}),t=s}return e}async function Ia(r,e,t){let n=await Yr(r,e,"variant");return Ys(t).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function Pa(r,e){if(e===!1||e==null||!r)return null;let t=typeof e=="boolean"?e.toString():e,n=r[t]||null;return n==null?null:Qt(n)}var Pf=9223372036854776e3,cy="9223372036854775808",ly=Object.prototype.propertyIsEnumerable;function uy(){return{ancestors:new WeakSet,remainingNodes:1e4}}function We(r,e){try{return kf(r,e,uy(),0)}catch{return[]}}function dy(r,e){let t=r.toString(),n=BigInt(cy);return r>=n||r<-n?(e?.debug(`Attribute ${t} is outside the int64 range; encoding it as a string`),{stringValue:t}):{intValue:t}}function Da(r,e,t,n){if(t.remainingNodes<=0)return{stringValue:Bs};if(t.remainingNodes--,Md(r))return{boolValue:r};if(typeof r=="bigint")return dy(r,e);if(typeof r=="number"){if(!Number.isFinite(r))return{stringValue:String(r)};if(Number.isInteger(r)){if(Number.isSafeInteger(r))return{intValue:String(r)};if("u"<typeof BigInt)return{stringValue:String(r)};let s=BigInt(r).toString();return r>=Pf||r<-Pf?(e?.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}}return{doubleValue:r}}if(typeof r=="string")return{stringValue:$e(r)};if(typeof r=="function")return{stringValue:Yd};if(typeof r=="symbol")return{stringValue:String(r)};if(typeof r=="object"&&r!==null){if(t.ancestors.has(r))return{stringValue:$s};if(n>=20)return{stringValue:Bs};if(r instanceof Date){let s=r.getTime(),i=Number.isFinite(s)?r.toISOString():String(r);return{stringValue:typeof i=="string"?$e(i):String(i)}}t.ancestors.add(r);try{try{let s=r.toJSON;if(typeof s=="function")return Da(s.call(r),e,t,n+1)}catch{}return ge(r)?{arrayValue:{values:fy(r,e,t,n+1)}}:{kvlistValue:{values:kf(r,e,t,n+1)}}}finally{t.ancestors.delete(r)}}return{stringValue:$e(String(r))}}function fy(r,e,t,n){let s=[],i=Math.min(r.length,1e3),o=0;for(;o<i&&t.remainingNodes>0;o++)try{let a=o in r?r[o]:void 0;if(Oe(a))continue;s.push(Da(a,e,t,n))}catch{s.push({stringValue:Se})}return r.length>o&&s.push({stringValue:Bs}),s}function kf(r,e,t,n){let s=[];for(let i in r)if(ly.call(r,i)){if(!i){e?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||t.remainingNodes<=0){e?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let o=r[i];if(Qo(o)||ze(o))continue;s.push({key:$e(i),value:Da(o,e,t,n)})}catch{s.push({key:$e(i),value:{stringValue:Se}})}}return s}function Xr(r,e,t){return{...Ve({},r.resourceAttributes),"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}var py=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function Qr(r,e){let t=Ve({},r),n={};for(let s of py)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s],delete t[s]);return[...We(t,e),...We(n,e)]}var xf={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 gy(r){if(r)return Object.prototype.hasOwnProperty.call(xf,r)?xf[r]:r}function La(r,e){let t=gy(r);return{...t?{"os.name":t}:{},...e?{"os.version":e}:{}}}var my={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}},bP=my.info;var Tt=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=ce(()=>{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 Zr(){return 1-.25+Math.random()*.25*2}var Te=1;function en(r,e,t,n){let s=Math.min(Math.max(0,e-1),6),i=r*2**s,o=n===void 0?i:Math.min(i,Math.max(n,r));return Math.round(o*t)}var Na="0000000000000000",Sy=Na+Na,yy=/^[0-9a-f]+$/;function by(r){let e=new Uint8Array(r),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")try{return t.getRandomValues(e),e}catch{}for(let n=0;n<r;n++)e[n]=Math.floor(256*Math.random());return e}function wy(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function Df(r){let e=wy(by(r));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Lf(){return Df(16)}function Nf(){return Df(8)}function Ff(r,e,t){return typeof r=="string"&&r.length===e&&r!==t&&yy.test(r)}function Uf(r){return Ff(r,32,Sy)}function $f(r){return Ff(r,16,Na)}var Ty=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Xs(r){let e=Bf(r);return e&&{traceId:e.traceId,spanId:e.spanId,flags:Ay(e.flags)}}function Ay(r){return 1&parseInt(r,16)?er:Ry}function Bf(r){if(typeof r!="string")return;let e=Ty.exec(r.trim());if(!e)return;let[,t,n,s,i,o]=e;if(t!=="ff"&&!(t==="00"&&o)&&!(!Uf(n)||!$f(s)))return{version:t,traceId:n,spanId:s,flags:i}}function Wf(r){return Bf(r)&&r.trim()}function Qs(r){return Array.isArray(r)&&r.length===1?r[0]:r}var er="01",Ry="00";function Hf(r,e,t=er){return`00-${r}-${e}-${t}`}var vy=32,Fa=512;function Zs(r){if(typeof r!="string")return;let e=r.trim();if(!e||/[^\x20-\x7e\t]/.test(e))return;let t=e.split(",");if(!(t.length>vy)){for(let n of t)if(n.trim()&&!n.includes("="))return;return e.length<=Fa?e:Oy(t)}}var My=128;function Oy(r){let e=[...r],t=()=>e.reduce((n,s)=>n+s.length,0)+e.length-1;for(let n=e.length-1;n>=0&&t()>Fa;n--)e[n].length>My&&e.splice(n,1);for(;e.length&&t()>Fa;)e.pop();return e.length?e.join(","):void 0}var tn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ei(r){return String(r)+"000000"}function Ua(r,e,t,n){let s="";return n&&(s=Object.keys(n).sort().map(o=>`${JSON.stringify(o)}:${JSON.stringify(n[o])}`).join(",")),`${r}\0${e}\0${t??""}\0${s}`}function jf(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function $a(r,e,t){return Xr(r,e,t)}function Ba(r,e,t,n){return{resourceMetrics:[{resource:{attributes:Qr(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function ti(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var Kf=1,rn=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushTimer=new Tt(()=>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 bt,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,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=Te,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 t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,s;try{n=t.attributes?{...t.attributes}:void 0,s=Ua(t.type,t.name,t.unit,n)}catch(c){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,c);return}let i=this._series.get(s);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(s,i)}let o=this._typeByName.get(t.name);o===void 0?this._typeByName.set(t.name,t.type):o!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,t.value);let a=this._activeTraceContext();a&&(i.exemplar={...a,value:t.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=Xs(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===er)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,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(tn.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[jf(t,tn)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=ge(t)?t:[t],s=e;for(let i of n)try{let o=i(s);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;s=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(en(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 t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=Zr()):(this._consecutiveFlushFailures=0,this._flushJitter=Te),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 Ba(this._buildMetrics(e),$a(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=ei(Date.now()),n=new Map;for(let s of e.values()){let i=Ua(s.type,s.name,s.unit,void 0),o=n.get(i);o||(o={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count"?o.sum={aggregationTemporality:Kf,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:Kf,dataPoints:[]},n.set(i,o));let a=We(s.attributes??{},this._logger),c=ei(s.windowStartMs),l=Cy(s.exemplar);if(s.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:t,asDouble:s.total??0,...l};o.sum.dataPoints.push(u)}else if(s.type==="gauge"){let u={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};o.gauge.dataPoints.push(u)}else if(s.hist){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:tn,...l};o.histogram.dataPoints.push(u)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let s=this._series.get(t);if(!s){this._admitNewSeries()&&this._series.set(t,n);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,n.windowStartMs),s.exemplar=s.exemplar??n.exemplar,s.type){case"count":s.total=(s.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(s.hist){s.hist.count+=n.hist.count,s.hist.sum+=n.hist.sum,s.hist.min=Math.min(s.hist.min,n.hist.min),s.hist.max=Math.max(s.hist.max,n.hist.max);for(let i=0;i<s.hist.bucketCounts.length;i++)s.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else s.hist=n.hist;break}}}};function Cy(r){return r?{exemplars:[{filteredAttributes:[],timeUnixNano:ei(r.timeMs),asDouble:r.value,traceId:r.traceId,spanId:r.spanId}]}:{}}var Gf="unknown";function At(r,e,t,n){return typeof r=="string"&&r.trim()?r.length>t?r.slice(0,t):r:(n?.debug(`${e} must be a non-empty string; using "${Gf}"`),Gf)}function tr(r){if(r==null)return;let e=r;if(r instanceof Date)try{e=r.getTime()}catch{return}if(!(typeof e!="number"||!Number.isFinite(e))&&!(e<0||e>9223372036854))return e}function zf(r,e,t){let n=tr(r);return n===void 0?(r!==void 0&&t?.debug("Span startTime is out of range or not a valid time; using the current time"),e):(e-n>864e5?t?.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&&t?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function ri(r,e){return r<e?e:r}function nn(r,e,t,n){let s=tr(r);return s===void 0?(r!==void 0&&n?.debug(`Span ${t} is out of range or not a valid time; using the derived time`),e):s}function si(){let r=globalThis.performance;return typeof r?.now=="function"?r.now():void 0}var rr=class{constructor(e,t,n){this._onEnd=t,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??er,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:si(),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=si();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,t){if(Oe(t)){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]=oi(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=Ve({},e);for(let n of Object.keys(t))this._writeAttribute(n,t[n])}return this}addEvent(e,t,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=t&&Jf(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:At(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:nn(n,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,t){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,...t&&{message:Wa(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:n,stack:s}=Ha(e);return this.addEvent(Iy,{"exception.type":t,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=At(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Hf(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 t=this._now(),n=nn(e,t,"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:ri(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Iy="exception",Py=4294967295;function ky(r){try{return typeof r=="string"?r:String(r)}catch{return Se}}function Rt(r){return typeof r!="number"||!Number.isFinite(r)||r<=0?0:Math.min(Math.floor(r),Py)}function xy(r,e){if(!e.length)return Object.keys(r);let t=e.filter(s=>Object.prototype.propertyIsEnumerable.call(r,s)),n=new Set(t);return[...t,...Object.keys(r).filter(s=>!n.has(s))]}function qf(r,e,t,n,s,i,o=[]){let a=0,c=0,l={};for(let p of xy(r.attributes,o)){let m=r.attributes[p];if(!Oe(m)){if(!e.has(p)){if(a>=t){c++;continue}a++}Object.defineProperty(l,p,{value:oi(m,i),enumerable:!0,writable:!0,configurable:!0})}}r.attributes=l,c&&(r.droppedAttributesCount=Rt(r.droppedAttributesCount)+c);let u=0,d=0,g=[];for(let p of r.events){if(u>=n){d++;continue}if(u++,p.attributes){let m=Jf(p.attributes,s,i);p.attributes=m.attributes,m.dropped&&(p.droppedAttributesCount=Rt(p.droppedAttributesCount)+m.dropped)}g.push(p)}r.events=g,d&&(r.droppedEventsCount=Rt(r.droppedEventsCount)+d),r.status?.message&&(r.status={...r.status,message:Wa(ky(r.status.message),i)})}var ii=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(){}},Yf=new ii,sn=class extends ii{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Dy(r){try{let e=r.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function it(r,e){let t=Qs(r?.parent)??e,n=typeof t=="string"||t==null?t:Vf(t,"traceparent"),s=Wf(n);if(!s)return Yf;let i=typeof t=="string"||t==null?r?.tracestate:Vf(t,"tracestate");return new sn(s,Zs(i))}function Vf(r,e){try{let t=r[e];return typeof t=="function"?t.call(r):void 0}catch{return}}function Wa(r,e){return r.length>e?r.slice(0,e):r}function oi(r,e){return ni(r,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function ni(r,e,t,n){if(r===null||typeof r!="object")return Oe(r)||t.remainingNodes<=0?r:(t.remainingNodes--,typeof r=="string"?Wa(r,e):r);if(t.ancestors.has(r))return $s;if(t.remainingNodes<=0||n>=20)return r;t.remainingNodes--,t.ancestors.add(r);try{if(r instanceof Date)return r;let s=Ly(r);if(s.selfDescribed)return Oe(s.value)?String(s.value):ni(s.value,e,t,n+1);if(ge(r)){let a=Math.min(r.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(ni(r[l],e,t,n+1))}catch{c.push(Se)}return r.length>a&&(c.length=r.length),c}let i={},o=0;for(let a of Object.keys(r)){if(o>=1e3)break;let c;try{c=ni(r[a],e,t,n+1)}catch{c=Se}a&&!Oe(c)&&o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return i}catch{return r}finally{t.ancestors.delete(r)}}function Ly(r){try{let e=r.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(r)}}catch{}return{selfDescribed:!1}}function Jf(r,e,t){let n;try{n=Object.keys(r)}catch{return{attributes:{},dropped:0}}let s={},i=0,o=0;for(let a of n){if(i>=e){o++;continue}let c;try{c=oi(r[a],t)}catch{c=Se}Oe(c)||(i++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:o}}function Xf(r,e){for(let t of Object.keys(r))r[t]=oi(r[t],e);return r}function on(r,e,t){return e===Yf?t(e):r.with(e,()=>t(e))}function Ha(r){try{let e=Dy(r);if(nt(r))return{type:r.name||"Error",message:r.message||"",...e};if(typeof r=="string")return{type:"string",message:r};if(r&&typeof r=="object"){let t=r;if(typeof t.message=="string")return{type:typeof t.name=="string"?t.name:"Object",message:t.message,...e}}return{type:typeof r,message:String(r)}}catch{return{type:typeof r,message:""}}}var ja={internal:1,server:2,client:3,producer:4,consumer:5},Ny={ok:1,error:2},Fy=1,Uy=256,$y=512;function By(r){let e=parseInt(r.traceFlags,16);return(Number.isFinite(e)?255&e:Fy)|Uy|(r.parentIsRemote?$y:0)}function ai(r){if(typeof r=="string")return $e(r);try{return $e(String(r))}catch{return Se}}function Wy(r){return r&&Object.prototype.hasOwnProperty.call(ja,r)?ja[r]:ja.internal}function Ka(r){let e=Math.floor(r),t=Math.round((r-e)*1e6);return t>=1e6&&(e+=1,t=0),String(e)+String(t).padStart(6,"0")}function Hy(r,e){let t={name:ai(r.name),timeUnixNano:Ka(r.timestamp)};if(r.attributes){let s=We(r.attributes,e);s.length&&(t.attributes=s)}let n=Rt(r.droppedAttributesCount);return n&&(t.droppedAttributesCount=n),t}function Qf(r,e){let t={traceId:r.traceId,spanId:r.spanId,name:ai(r.name),kind:Wy(r.kind),startTimeUnixNano:Ka(r.startTime),endTimeUnixNano:Ka(r.endTime),flags:By(r)};r.parentSpanId&&(t.parentSpanId=r.parentSpanId),r.traceState&&(t.traceState=ai(r.traceState));let n=We(r.attributes,e);n.length&&(t.attributes=n),r.events.length&&(t.events=r.events.map(o=>Hy(o,e)));let s=Rt(r.droppedAttributesCount);s&&(t.droppedAttributesCount=s);let i=Rt(r.droppedEventsCount);return i&&(t.droppedEventsCount=i),r.status&&(t.status={code:Ny[r.status.code],...r.status.message&&{message:ai(r.status.message)}}),t}function Zf(r,e,t){return Xr(r,e,t)}function ep(r,e,t,n,s){return{resourceSpans:[{resource:{attributes:Qr(e,s)},scopeSpans:[{scope:{name:t,version:n},spans:r}]}]}}var tp=8;function ci(){return si()??Date.now()}function Ga(r){try{return r instanceof rr}catch{return!1}}function rp(r,e){let t=Xs(r);if(t)return{traceId:t.traceId,parentSpanId:t.spanId,traceState:Zs(e),traceFlags:t.flags,isRemote:!0}}function jy(r){try{return typeof r.traceparent=="function"}catch{return!1}}function Ky(r){return!!r.attributes&&typeof r.attributes=="object"&&!Array.isArray(r.attributes)&&Array.isArray(r.events)&&r.name!==void 0&&r.kind!==void 0&&r.startTime!==void 0&&r.endTime!==void 0}function li(r,e,t){r[e]!==t&&(r[e]=t)}function Gy(r,e){try{let t=Object.getOwnPropertyDescriptors(r);for(let n of["traceId","spanId","parentSpanId","traceState"])t[n]={value:e[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(r),t)}catch{return r}}var an=class{constructor(e,t,n,s,i,o){this._instance=e,this._config=t,this._logger=n,this._getContext=s,this._contextManager=i,this._onSpanQueued=o,this._queue=[],this._flushTimer=new Tt(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._retryAfter=new bt,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){if(this._instance.isDisabled||this._instance.optedOut)return it(t,this._contextManager.active());let n=Qs(t?.parent);if(n&&typeof n!="string"&&!Ga(n)){if(jy(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),it(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(n,t);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`),it(t,this._contextManager.active());let i=Date.now(),o=zf(t?.startTime,i,this._logger),a=Nf();this._liveSpans.set(a,ci());let c=this._autoContextAttributes();return new rr({traceId:s?.traceId??Lf(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:At(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:Ve({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:o,backdated:o!==i,clockAnchor:tr(t?.startTime)===void 0?s?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this.startSpan(e,s);try{let a=on(this._contextManager,o,i);return Zd(a)?a.then(c=>(o.end(),c),c=>{throw this._recordCallbackError(o,c),o.end(),c}):(o.end(),a)}catch(a){throw this._recordCallbackError(o,a),o.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}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=Te,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if(typeof e=="string"){let s=rp(e,t?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(Ga(e))return e.childContext();let n=this._contextManager.active();if(Ga(n))return n.childContext();if(n instanceof sn)return rp(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 t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof rr))return;let{type:n,message:s,stack:i}=Ha(t);e.addEvent("exception",{"exception.type":n,"exception.message":s,...i&&{"exception.stacktrace":i}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=ci()-this._config.maxSpanAgeMs,t=0;for(let[n,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(n),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){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,t);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 t=e.droppedAttributesCount??0,n=e.droppedEventsCount??0,s=0;for(let i of e.events)s+=i.droppedAttributesCount??0;(t||n||s)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${n} events, ${s} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},i={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},o=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},c=e.status&&{...e.status},l=e,u=e;try{for(let p of this._config.beforeSpanSend){let m=p(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:i.attributes,droppedEventsCount:i.events},!Ky(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=At(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=tr(u.startTime)??s.startTime,u.endTime=ri(tr(u.endTime)??s.endTime,u.startTime);let g=[];for(let p of u.events)try{g.push({...p,name:At(p.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:nn(p.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=g,qf(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,o),u}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,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{li(e,"traceId",t.traceId),li(e,"spanId",t.spanId),li(e,"parentSpanId",t.parentSpanId),li(e,"traceState",t.traceState)}catch{return Gy(e,t)}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),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 t=[];for(let n of e)try{t.push(Qf(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 t}_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 t=Xf(Zf(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),i=this._queue.length,o=0,a=1/0,c=this._generation;try{for(;i>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return o+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,d=Math.max(1,Math.min(u,a,i,this._queue.length)),g=this._queue.slice(0,d),p=this._encodeBatch(g);if(!p.length){this._queue.splice(0,d),i-=d,o+=d,this._resetHeadBatchBudget();continue}let m=ci()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(ep(p,t,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Te,this._resetHeadBatchBudget(),this._queue.splice(0,d),i-=d,o+=d,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(h.kind==="too-large"){if(d===1){this._queue.splice(0,1),i-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=Te,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=Zr(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=ci()+this._nextFlushDelay()),this._headBatchFailures<tp)return this._logger.debug("Span export failed; retrying on the next flush",h.error),o;if(this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${tp} times in a row`),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",h.error),this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=Te,this._resetHeadBatchBudget(),this._recordDrop(d,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(en(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var cn=class{active(){return this._active}with(e,t){let n=this._active;this._active=e;try{return t()}finally{this._active=n}}};var zy=5e3,Vy=512,qy=2048,Yy=128,Jy=128,Xy=128,Qy=8192,Zy=1e4,eb=36e5;function ot(r,e){return typeof r=="number"&&Number.isInteger(r)&&r>=1?r:e}var np=["service.name","service.version","deployment.environment"];function tb(r){if(!(!r||typeof r!="object"||Array.isArray(r)))try{if(np.every(t=>!(t in r)||typeof r[t]=="string"))return r;let e={...r};for(let t of np)t in e&&typeof e[t]!="string"&&delete e[t];return e}catch{return}}function rb(r,e){if(!r)return[];let t=[r].flat().filter(s=>!!s),n=t.filter(s=>typeof s=="function");return n.length!==t.length&&e?.critical(`beforeSpanSend: ignoring ${t.length-n.length} of ${t.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function za(r,e,t){let n=Ve({...e},tb(r?.resourceAttributes)),s=ot(r?.maxExportBatchSize,Vy);return{serviceName:n?.["service.name"]??r?.serviceName,serviceVersion:n?.["service.version"]??r?.serviceVersion,environment:n?.["deployment.environment"]??r?.environment,resourceAttributes:n,beforeSpanSend:rb(r?.beforeSpanSend,t),maxAttributesPerSpan:ot(r?.maxAttributesPerSpan,Yy),maxEventsPerSpan:ot(r?.maxEventsPerSpan,Jy),maxAttributesPerEvent:Xy,maxAttributeValueLength:ot(r?.maxAttributeValueLength,Qy),flushIntervalMs:ot(r?.flushIntervalMs,zy),maxExportBatchSize:s,maxQueueSize:Math.max(ot(r?.maxQueueSize,qy),s),maxLiveSpans:ot(r?.maxLiveSpans,Zy),maxSpanAgeMs:ot(r?.maxSpanAgeMs,eb)}}var Va=require("node:fs"),op=require("node:fs/promises"),Ya=require("node:path"),ap=require("node:readline"),ui=new q.ReduceableCache(25),ln=new q.ReduceableCache(20),Ja=7,nb=1e3,sb=1e4,qa=10485760;async function cp(r,e=op.open,t){let n={},s;try{s=process.cwd()}catch{}for(let a=r.length-1;a>=0;a--){let c=r[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||lb(l)||ub(c)||!(0,Ya.isAbsolute)(l)&&s===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let i=Object.keys(n);if(i.length==0)return r;let o=[];for(let a of i){let c=lp(a,s);if(c===void 0||ln.get(c))continue;let l=n[a];if(!l)continue;l.sort((g,p)=>g-p);let u=fb(l);if(u.every(g=>db(c,g)))continue;let d=pb(ui,c,{});o.push(ob(a,u,d,c,e,t))}return await Promise.all(o).catch(()=>{}),r&&r.length>0&&ab(r,ui,s),ui.reduce(),r}async function ib(r,e,t){let n,s=!1;try{n=await e(r,Va.constants.O_RDONLY|Va.constants.O_NONBLOCK);let i=await n.stat();return i.isFile()?i.size>qa?void t?.debug(`Skipping source context for oversized file ${r}: ${i.size} bytes exceeds ${qa}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function ob(r,e,t,n,s,i){let o=await ib(r,s,i);if(o===void 0)return void ln.set(n,1);let a=o;return new Promise(c=>{let l=!1;function u(w){l||(l=!0,w?.destroy(),a.close().then(c,c))}let d;try{d=a.createReadStream({autoClose:!1,start:0,end:qa-1})}catch{ln.set(n,1),u();return}let g;try{g=(0,ap.createInterface)({input:d})}catch{ln.set(n,1),u(d);return}let p=0,m=0,h=e[m];if(h===void 0)return void u(d);let _=h[0],E=h[1];function y(){ln.set(n,1),g.close(),g.removeAllListeners(),u(d)}d.on("error",y),g.on("error",y),g.on("close",()=>u(d)),g.on("line",w=>{if(p++,!(p<_)&&(t[p]=gb(w,0),p>=E)){if(m===e.length-1){g.close(),g.removeAllListeners();return}m++;let R=e[m];if(R===void 0){g.close(),g.removeAllListeners();return}_=R[0],E=R[1]}})})}function ab(r,e,t){for(let n of r)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=lp(n.filename,t),i=s===void 0?void 0:e.get(s);if(i===void 0)continue;cb(n.lineno,n,i)}}function cb(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let s=up(r);s<r;s++){let i=t[s];if(i===void 0)return void sp(e);e.pre_context.push(i)}if(t[r]===void 0)return void sp(e);e.context_line=t[r];let n=dp(r);e.post_context=[];for(let s=r+1;s<=n;s++){let i=t[s];if(i===void 0)break;e.post_context.push(i)}}function sp(r){delete r.pre_context,delete r.context_line,delete r.post_context}function lb(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function ub(r){return r.lineno!==void 0&&r.lineno>sb||r.colno!==void 0&&r.colno>nb}function lp(r,e){return(0,Ya.isAbsolute)(r)?JSON.stringify([null,r]):e===void 0?void 0:JSON.stringify([e,r])}function db(r,e){let t=ui.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function fb(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=ip(t),s=[];for(;;){if(e===r.length-1){s.push(n);break}let i=r[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+Ja:(s.push(n),n=ip(i)),e++}return s}function ip(r){return[up(r),dp(r)]}function up(r){return Math.max(1,r-Ja)}function dp(r){return r+Ja}function pb(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function gb(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let s=Math.max(e-60,0);s<5&&(s=0);let i=Math.min(s+140,n);return i>n-5&&(i=n),i===n&&(s=Math.max(i-140,0)),t=t.slice(s,i),s>0&&(t=`...${t}`),i<n&&(t+="..."),t}var nr=require("path");function fp(r=process.cwd()){let e=nr.sep==="\\",t=s=>e?s.replace(/\\/g,"/"):s,n=t(r);return async s=>{for(let i of s)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,nr.isAbsolute)(i.filename)&&(i.filename=t((0,nr.relative)(n,t(i.filename))));return s}}var pp="5.56.2";var Ye={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var at=class r{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,t={}){let n=this._flags[e];return this._recordAccess(e),n?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let s of e){let i=this._flags[s];i?t[s]=i:n.push(s)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,s]of Object.entries(this._flags)){let i=s.enabled===!1?!1:s.variant??!0;e[`$feature/${n}`]=i,s.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({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 t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,s={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(Ye.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(Ye.QUOTA_LIMITED),t===void 0&&i.push(Ye.FLAG_MISSING),i.length>0&&(s.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}};var mb=6e4;function gp(r){return r==="client"||r==="server"?r:"all"}function hb(r,e){return r===e||r==="all"||e==="all"}var vt=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function _b(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var He=class r extends Error{constructor(e){super(e),_b(this,r)}},di=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:s,host:i,customHeaders:o,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=o,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(e,t={},n={},s={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:s,evaluationCache:i}}async getFeatureFlag(e,t,n={},s={},i={}){await this.loadFeatureFlags();let o,a;if(!this.loadedSuccessfullyOnce)return o;if(a=this.featureFlagsByKey[e],a!==void 0){let c=this.createEvaluationContext(t,n,s,i);try{o=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(l){l instanceof He||l instanceof v?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${e}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${l}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},s={},i=this.featureFlags.length==0,o=t?t.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(o.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(s[c.key]=u)}catch(l){l instanceof He||l instanceof v?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),i=!0}})),{response:n,payloads:s,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:s,skipLoadCheck:i=!1}=n;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};t=this.withEvaluationSnapshot(t),e=t.definitions.featureFlagsByKey[e.key]??e;let o;o=s!==void 0?s:await this.computeFlagValueLocally(e,t);let a=Pa(e.filters?.payloads,o);return{value:o,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:s,personProperties:i,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new v("Flag has experience continuity enabled");let c=(e.filters||{}).aggregation_group_type_index;if(c!=null){let l=t.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${e.key}`)),new v("Flag has unknown group type index");if(!(l in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=o[l];return await this.matchFeatureFlagProperties(e,s[l],u,t)}{let l=this.getBucketingValueForFlag(e,n,i);if(l===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 v(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let s=n?.$device_id;return s==null||s===""?void 0:s}return t}async evaluateFlagDependency(e,t,n){let{evaluationCache:s}=n,i=e.key;if(!n.definitions.featureFlagsByKey)throw new v("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new v(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new v(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new v(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let c of o){if(!(c in s)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let d=await this.computeFlagValueLocally(u,n);s[c]=d}catch(d){throw new v(`Error evaluating flag dependency '${c}' for flag '${i}': ${d}`)}else s[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))s[c]=!1;else throw new v(`Missing flag dependency '${c}' for flag '${i}'`)}if(s[c]==null)throw new v(`Dependency '${c}' could not be evaluated`)}let a=s[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,s){s=this.withEvaluationSnapshot(s);let i=e.filters||{},o=await Ca(i.holdout,t);if(o!==void 0)return o;let a=i.groups||[],c=i.aggregation_group_type_index,l=i.early_exit??!1,{groups:u,groupProperties:d}=s,g=!1,p;for(let m of a)try{let h=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,_=n,E=t;if(h!==c&&h!=null){let w=s.definitions.groupTypeMapping[String(h)];if(!w||!(w in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(w in d)){g=!0;continue}_=d[w],E=u[w]}let y=await this.isConditionMatch(e,E,m,_,s);if(y==="match"){let w=m.variant,R=i.multivariate?.variants||[];p=w&&R.some(P=>P.key===w)?w:await this.getMatchingVariant(e,E)||!0;break}if(l&&y==="out_of_rollout_bound"){if(g)break;return!1}}catch(h){if(h instanceof He)throw h;if(h instanceof v)g=!0;else throw h}if(p!==void 0)return p;if(g)throw new v("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,s,i){i=this.withEvaluationSnapshot(i);let o=i.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,d=!1;if(u==="cohort"){let g=await hp(l,s,o.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,s,i),o.propertyMatchingVersion);d=l.operator==="not_in"?!g:g}else d=u==="flag"?await this.evaluateFlagDependency(l,s,i):mp(l,s,c,o.propertyMatchingVersion);if(!d)return"no_match"}if(a==null)return"match"}return a!=null&&await Yr(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return Ia(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return Ys(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let t=new Set(this.evaluationContexts);return e.filter(n=>{let s=n.evaluation_contexts??n.evaluation_tags;return!s||s.length===0?!0:s.some(i=>t.has(i))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?gp(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>hb(gp(t.evaluation_runtime),e)).map(t=>t.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),n=t.reduce((o,a)=>(o[a.key]=a,o),{}),s=new Set(t.map(o=>o.key)),i=new Set(e.flags.filter(o=>!s.has(o.key)).map(o=>o.key));this.featureFlags=t,this.featureFlagsByKey=n,this.filteredOutFlagKeys=i,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.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 t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!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(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).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(mb,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 t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new vt(`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 vt(`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 vt(`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 t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let s=n.group_type_mapping||{},i=n.minimal_flag_called_events===!0,o={flags:n.flags??[],group_type_mapping:s,cohorts:n.cohorts||{},minimal_flag_called_events:i,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:s,minimalFlagCalledEvents:i};if(this.updateFlagState(o),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(o)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof vt&&this.onError?.(e)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new vt("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=ce(()=>{i.abort()},this.timeout),t.signal=i.signal}let s=()=>clearTimeout(n);try{let i=this.fetch,o=await i(e,t);return o.status!==200?(s(),o):{status:o.status,headers:o.headers,body:o.body,text:async()=>{try{return await o.text()}finally{s()}},json:async()=>{try{return await o.json()}finally{s()}}}}catch(i){throw s(),i}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await st(t,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};function mp(r,e,t,n){return Oa(r,e,{warnFunction:t,propertyMatchingVersion:n})}function Eb(r,e){if(!(r in e))throw new He(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function hp(r,e,t,n=!1,s,i){let o=String(r.value);Eb(o,t);let a=t[o];return _p(a,e,t,n,s,i)}async function _p(r,e,t,n=!1,s,i){if(!r)return!0;let o=r.type,a=r.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await _p(l,e,t,n,s,i);if(o==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof He)throw u;if(u instanceof v)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new v("Can't match cohort without a given cohort property value");return o==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await hp(l,e,t,n,s,i);else if(l.type==="flag"){if(!s)throw new v(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await s(l)}else u=mp(l,e,void 0,i);let d=l.negation||!1;if(o==="AND"){if(!u&&!d||u&&d)return!1}else if(u&&!d||!u&&d)return!0}catch(u){if(u instanceof He)throw u;if(u instanceof v)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new v("can't match cohort without a given cohort property value");return o==="AND"}var Sb=["--unhandled-rejections","--unhandled_rejections"],yb=new Set(["throw","strict","warn","warn-with-error-code","none"]),bb=[...globalThis.process?.execArgv??[]],wb=globalThis.process?.env?.NODE_OPTIONS;function Tb(r){let e=[],t="",n=!1;for(let s=0;s<r.length;s++){let i=r[s];i==="\\"&&n&&s+1<r.length?t+=r[++s]:i!==" "||n?i==='"'?n=!n:t+=i:t&&(e.push(t),t="")}return t&&e.push(t),e}function Ep(r){let e;for(let t=0;t<r.length;t++){let n=r[t],s=Sb.find(o=>n===o||n.startsWith(`${o}=`));if(!s)continue;let i=n===s?r[++t]:n.slice(s.length+1);yb.has(i)&&(e=i)}return e}function Ab(r=bb,e=wb){return Ep(r)??Ep(Tb(e??""))??"throw"}var Sp=Ab();function yp(r,e,t){r(e,{mechanism:{type:t==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Rb(r,e){let t=!1;return Object.assign((n,s)=>{let i=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length;yp(r,n,s),!t&&i===0&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function bp(r,e,t=Sp){let n=globalThis.process;if(n){if(t==="strict")return void n.on("uncaughtExceptionMonitor",(s,i)=>yp(r,s,i));n.on("uncaughtException",Rb(r,e))}}function wp(r,e=Sp){let t=globalThis.process;!t||e==="throw"||e==="strict"||e==="warn-with-error-code"||t.on("unhandledRejection",n=>{r(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var vb=2e3,Xa=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Ps({...kd(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return xr(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,s,i){let o={...i},a=e.buildFromUnknown(t,n);a.$exception_list=await e.modifyFrames(a.$exception_list);let c=q.getInjectedReleaseId();return c&&(o.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(bp(this.onException.bind(this),this.onFatalError.bind(this)),wp(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(vb),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},Mt=Xa;var Mb=/^[0-9a-f]{32}$/i,Ob=/^[0-9a-f]{16}$/i,Cb;async function Tp(){try{let e=(await(Cb??=import("@opentelemetry/api"))).trace.getActiveSpan()?.spanContext(),t=e?.traceId,n=e?.spanId;if(typeof t=="string"&&typeof n=="string"&&Mb.test(t)&&Ob.test(n)&&!/^0+$/.test(t)&&!/^0+$/.test(n))return{$trace_id:t.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var fi=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function Ib(r){return r==="v0"||r==="v1"}function Ap(){let r="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Ib(r)?r:"v0"}var Pb="$ai_",un="analytics";function Rp(r){return typeof r.event=="string"&&r.event.startsWith(Pb)}var sr=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:s}){super(r.buildMessage(e,t,n,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=s}static buildMessage(e,t,n,s){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return s instanceof Error&&(i+=` (${s.message})`),i}};function Qa(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function kb(r){return typeof r=="string"?r:void 0}var xb=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Qa},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Qa},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Qa},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:kb}],Db=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Lb(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Nb(r){if(typeof r=="string"){let t=new Date(r);if(Number.isNaN(t.getTime()))return new Date().toISOString();let n=t.toISOString(),s=r.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function vp(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function Fb(r){let t={...Lb(r.properties)?r.properties:{}},n={};for(let{property:i,optionKey:o,coerce:a}of xb)if(i in t){let c=a(t[i]);c!==void 0&&(n[o]=c),delete t[i]}let s={};for(let{property:i,field:o}of Db)if(i in t){let a=t[i];typeof a=="string"&&(s[o]=a),delete t[i]}return delete t.$lib,delete t.$lib_version,vp(t,"$set",r.$set),vp(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:Nb(r.timestamp),...s,options:n,properties:t}}function Mp(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(Fb)};return t&&(n.historical_migration=!0),n}var Ub="/i/v1/analytics/events",$b=3e4,Bb=new Set([408,500,502,503,504]),pi=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??$b,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(s=>ce(s,n))),this.generateRequestId=t.generateRequestId??ae,this.compress=t.compress??zr}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=Mp(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${Ub}`,o=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,d=rt({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),g,p;try{g=await this.sendOnce(i,d,l,t);let{response:m,signal:h}=g,{status:_}=m;if(_<200||_>=300)if(!u&&Bb.has(_)){let E=this.parseRetryAfter(m);await g.waitFor(g.cancelBody()).catch(()=>{}),p=this.backoffDelay(l,E)}else{let E=await this.buildHttpError(m,_,g.waitFor);return this.surfaceBatchFailure(t,o,a,E)}else{let E;try{E=await g.waitFor(this.parseResponse(m))}catch(R){if(h.aborted)throw R;return this.surfaceBatchFailure(t,o,a,new Error(`Capture V1 returned an unparseable ${_} response body`))}let y=this.classify(a,E,o);if(y.length===0)return this.surfacePartialDrops(t,o);if(u)return void this.onError(new sr({requestId:t,drops:o,retryExhausted:y.map(R=>R.uuid)}));a=y;let w=this.parseRetryAfter(m);p=this.backoffDelay(l,w)}}catch(m){if(g&&!g.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(t,o,a,m);p=this.backoffDelay(l)}finally{g?.cleanup()}p!==void 0&&await this.sleep(p)}}async sendOnce(e,t,n,s){let i=this.buildHeaders(n,s),o=t;if(this.config.compressionEnabled){let d=await this.compress(t,this.config.isDebug);d!==null&&(o=d,i["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((d,g)=>{l=ce(()=>{let p=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);p.name="AbortError",g(p),a.abort(p)},this.config.requestTimeoutMs)});try{let d=this.fetchFn(e,{method:"POST",headers:i,body:o,signal:a.signal}),g=!1;d.then(E=>{a.signal.aborted&&!g&&this.cancelBody(E)}).catch(()=>{});let p=await Promise.race([d,u]);g=!0,c="while reading the response body";let m=!1,h,_=()=>h??=this.cancelBody(p);return{response:p,signal:a.signal,waitFor:E=>Promise.race([E,u]),cancelBody:_,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&_())}}}catch(d){throw clearTimeout(l),d}}buildHeaders(e,t){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":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(s["User-Agent"]=this.config.userAgent),s}classify(e,t,n){let s=t.results??{},i=[];for(let o of e){let a=s[o.uuid];a&&(a.result==="drop"?n.push({uuid:o.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(o))}return i}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let o=parseInt(n,10);return Number.isFinite(o)&&o>0?1e3*o:void 0}let s=Date.parse(n);if(Number.isNaN(s))return;let i=s-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);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,t,n){let s="";try{s=(await n(e.text())).slice(0,512)}catch{}let i=s?`: ${s}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,n,s){this.onError(new sr({requestId:e,drops:t,retryExhausted:n.map(i=>i.uuid),cause:s}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new sr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var Ot="ai-capture",gi="/i/v0/ai/batch/";var Hb=new TextEncoder;function ec(r){return Hb.encode(rt(r)).length}function Op(r,e=8388608,t=5242880){let n=[],s=[],i=[],o=0;for(let a of r){if(a===void 0)continue;let c=ec(a);if(c>e){s.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}i.length>0&&o+c>t&&(n.push(i),i=[],o=0),i.push(a),o+=c}return i.length>0&&n.push(i),{batches:n,dropped:s}}var jb=100,Cp=3e4,Kb=5e4,Gb=50,zb=500,Vb="https://us.i.posthog.com",Ip=new Set;function hi(r,e){Ip.has(r)||(Ip.add(r),console.warn(`[PostHog] ${e}`))}function qb(r){return typeof r=="string"?r.trim():""}function Yb(r){return(typeof r=="string"?r.trim():"")||void 0}function Jb(r){return(typeof r=="string"?r.trim():"")||Vb}function Xb(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function Qb(r){if(!r)return{};let e={};for(let[n,s]of Object.entries(r))e[`$feature/${n}`]=s;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var _i=class extends Vr{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){let n=qb(e),s={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:Jb(t.host),personalApiKey:Yb(t.secretKey??t.personalApiKey)};if(super(n,s),this._memoryStorage=new fi,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=Ap(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,jb):s.featureFlagsPollingInterval===null?null:Cp,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 di({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:n,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:o=>{this._events.emit("error",o)},onLoad:o=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:o=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments}))}this.errorTracking=new Mt(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||Kb}enqueue(e,t,n,s){super.enqueue(e,t,n,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:Nr([t,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 t=this._flushEventsAndSpans(e),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let o,a=new Promise(c=>{o=c});try{e(a)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??zb,s=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??Gb;this._waitUntilCycle.timer=ce(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&Rp(e)?"ai":un}persistedQueueKeyForRoute(e){return e===Ot?de.AiCaptureQueue:e==="ai"?de.AiQueue:de.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[un,"ai"]:[un];return this._aiCaptureRouteActive&&e.push(Ot),e}getBatchEndpointPath(e){return e===Ot?gi:super.getBatchEndpointPath(e)}async sendBatch(e,t,n=un){if(n===Ot)return this.sendAiCaptureBatch(e,t);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let s=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,t){let{batches:n,dropped:s}=Op(e);for(let{event:i,bytes:o}of s){let a=`Event ${i} (${o} bytes) exceeds the ${8388608/1048576}MiB limit for ${gi}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let i of n)await this.sendAiSubBatch(i,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,Ot)}catch(n){if(!Zt(n))throw n;if(e.length===1){let[i]=e,a=`Event ${typeof i.event=="string"?i.event:"unknown"} (${ec(i)} bytes) was rejected with 413 by ${gi} 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),t),await this.sendAiSubBatch(e.slice(s),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new pi({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,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return pp}get metrics(){return this._metrics||(this._metrics=new rn(this,ti(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new cn}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 an(this,za(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,t){return this._tracesPipeline?.startSpan(e,t)??it(t,this._spanContextManager.active())}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this._tracesPipeline;return o?s?o.withSpan(e,s,i):o.withSpan(e,i):on(this._spanContextManager,it(s,this._spanContextManager.active()),i)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,s,i){return this.addPendingPromise(this._prepareEventMessage(t,s).then(({distinctId:o,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},d={distinctId:o,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,d,u,i):this.enqueue(e,d,u,i)}).catch(o=>{o&&console.error(o)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}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 t=wt(e.uuid,ae);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=wt(e.uuid,ae);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){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,t,void 0,Ot)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let s={};Object.keys(t).length>0&&(s.$set=t),Object.keys(n).length>0&&(s.$set_once=n),this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:t}){let n=Xb(t);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=Cp){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{s(),t(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),s(),t(i>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let S=this._flagOverrides[e];if(S===void 0)return;let T=this._payloadOverrides?.[e];return{key:e,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:T}}let{groups:o,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,d=this.addLocalPersonAndGroupProperties(t,o,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p,m=!1,h,_,E,y,w,R,P;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let S=this.featureFlagsPoller?.featureFlagsByKey[e];if(S)try{let T=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(S,g,{matchValue:s});if(T){m=!0;let b=T.value;y=S.id,R="Evaluated locally",P=S.has_experiment,p={key:e,enabled:b!==!1,variant:typeof b=="string"?b:void 0,payload:T.payload??void 0,reason:R,reasonCode:S.active===!1?"flag_disabled":void 0}}}catch(T){if(T instanceof He||T instanceof v)this._logger?.info(`${T.name} when computing flag locally: ${e}: ${T.message}`);else throw T}}if(!m&&!c){let S=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,a,[e]);if(S===void 0)E=Ye.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=S.minimalFlagCalledEvents===!0,h=S.requestId,_=S.evaluatedAt;let T=[];S.errorsWhileComputingFlags&&T.push(Ye.ERRORS_WHILE_COMPUTING),S.quotaLimited?.includes("feature_flags")&&T.push(Ye.QUOTA_LIMITED);let b=S.flags[e];if(b===void 0)T.push(Ye.FLAG_MISSING);else{y=b.metadata?.id,w=b.metadata?.version,R=b.reason?.description??b.reason?.code,P=b.metadata?.has_experiment;let C;if(b.metadata?.payload!==void 0)try{C=JSON.parse(b.metadata.payload)}catch{C=b.metadata.payload}p={key:e,enabled:b.enabled,variant:b.variant??void 0,payload:C,reason:R,reasonCode:b.reason?.code}}T.length>0&&(E=T.join(","))}}if(i){let S=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,T={$feature_flag:e,$feature_flag_response:S,$feature_flag_id:y,$feature_flag_version:w,$feature_flag_reason:R,locally_evaluated:m,[`$feature/${e}`]:S,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():_};if(P!==void 0&&(T.$feature_flag_has_experiment=P),m&&this.featureFlagsPoller){let b=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();b!==void 0&&(T.$feature_flag_definitions_loaded_at=b)}E&&(T.$feature_flag_error=E),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:S,groups:o,disableGeoip:a,properties:T})}return p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[e]}),p}async getFeatureFlag(e,t,n){hi("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,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s!==void 0)return s.enabled===!1?!1:s.variant??!0}async getFeatureFlagPayload(e,t,n,s){if(hi("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...s,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:s,options:i}=this._resolveDistinctId(t,n);return s?this._getFeatureFlagResult(e,s,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){hi("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,t,{...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,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);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,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:o,flagKeys:a}=s||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),m={},h={},_=!0;if(p&&(m=p.response,h=p.payloads,_=p.fallbackToFlags),_&&!c){let E=await super.getFeatureFlagsAndPayloadsStateless(g.distinctId,g.groups,l,u,o,a);m={...m,...E.flags||{}},h={...h,...E.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,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:o}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=a?new Set(a):void 0,m={},h,_,E=!1,y=!1,w=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),R=new Set;if(w)for(let[S,T]of Object.entries(w.response)){let b=this.featureFlagsPoller?.featureFlagsByKey[S];m[S]={key:S,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:w.payloads[S],id:b?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:b?.has_experiment},R.add(S)}let P=p!==void 0&&Array.from(p).some(S=>this.featureFlagsPoller?.featureFlagsByKey[S]===void 0);if((w?w.fallbackToFlags||P:!0)&&!c){let S=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,o,a);if(S){this._minimalFlagCalledEvents=S.minimalFlagCalledEvents===!0,h=S.requestId,_=S.evaluatedAt,E=!!S.errorsWhileComputingFlags,y=Array.isArray(S.quotaLimited)&&S.quotaLimited.includes("feature_flags");for(let[T,b]of Object.entries(S.flags)){if(R.has(T))continue;let C;if(b.metadata?.payload!==void 0)try{C=JSON.parse(b.metadata.payload)}catch{C=b.metadata.payload}m[T]={key:T,enabled:b.enabled,variant:b.variant,payload:C,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[S,T]of Object.entries(this._flagOverrides)){if(T===void 0){delete m[S];continue}let b=m[S];m[S]={key:S,enabled:T!==!1,variant:typeof T=="string"?T: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[S,T]of Object.entries(this._payloadOverrides)){let b=m[S];b&&(m[S]={...b,payload:T})}if(p!==void 0)for(let S of Object.keys(m))p.has(S)||delete m[S];return new at({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:m,requestId:h,evaluatedAt:_,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:E,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:s,groups:i,disableGeoip:o,properties:a}=e,c=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([d],[g])=>d<g?-1:d>g?1:0))}`:"",l=`${n}_${s}${c}`,u=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,u),!u.has(l)){for(u.add(l);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:t,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:o})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=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=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(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 t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await st(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await st(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;s=ce(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(t,n)}catch(i){this._events.emit("error",i);return}finally{s&&clearTimeout(s)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},s={};for(let[i,o]of Object.entries(e))if(Cd(o)&&t&&i in t){let a={};for(let[c,l]of Object.entries(o))a[String(c)]=String(l);s[String(i)]=a}else n[String(i)]=String(o);return{personProperties:n,groupProperties:s}}async getFeatureFlagsForEvent(e,t,n,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=s?.personProperties||{},o=s?.groupProperties||{},a=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,i,o,n)).flags}addLocalPersonAndGroupProperties(e,t,n,s){let i={...n||{}},o={};if(t)for(let a of Object.keys(t))o[a]={$group_key:t[a],...s?.[a]||{}};return{allPersonProperties:i,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,s){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,t,n,s,i){if(!Mt.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");this.addPendingPromise(Mt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,n).then(a=>this._capturePreparedEvent({...a,uuid:s,flags:i},!1)))}}async captureExceptionImmediate(e,t,n,s){if(!Mt.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(Mt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,n).then(o=>this.captureImmediate({...o,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:s,properties:i,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d}=e,g=this.context?.get(),p=t.includeContextProperties??!0,m=n||g?.distinctId,h=p?{...this.props,...g?.properties||{},...i||{}}:{...i||{}};s==="$exception"&&!("$trace_id"in h||"$span_id"in h)&&Object.assign(h,await Tp()),m||(m=ae(),h.$process_person_profile=!1),p&&g?.sessionId&&!h.$session_id&&(h.$session_id=g.sessionId);let _=this._shouldSendMinimalFlagCalledEvent(s,h)?Kr(h):h,E=this._runBeforeSend({distinctId:m,event:s,properties:_,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d});if(!E)return Promise.reject(null);let y=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){hi("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let w=typeof c=="object"?c:void 0,R=await this.getFeatureFlagsForEvent(E.distinctId,o,u,w);return Qb(R)}return{}}).catch(()=>({})).then(w=>{let R=E.groups||o;return{...w,...E.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return E.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof y.$raw_user_agent=="string"&&Pd(y.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(E.event="$bot_pageview",y.$browser_type="bot"),{distinctId:E.distinctId,event:E.event,properties:y,options:{timestamp:E.timestamp,disableGeoip:E.disableGeoip,uuid:E.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],s=e;for(let i of n)try{if(s=i(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let o=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}catch(o){return this._logger.error(`Error in before_send function for event '${e.event}':`,o),null}return s}};var Pp=require("node:async_hooks"),Ei=class{constructor(){this.storage=new Pp.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.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 kp=require("node:async_hooks"),Si=class{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new kp.AsyncLocalStorage}};var xp=require("node:zlib"),Dp=require("node:util"),Zb=(0,Dp.promisify)(xp.gzip);async function Lp(r,e=!0){try{let t=await Zb(r);return new Uint8Array(t)}catch(t){return e&&console.error("Failed to gzip compress data",t),null}}var yi=require("node:os");function Np(){let r,e;try{r=(0,yi.platform)(),e=(0,yi.release)()}catch{}return La(r,e)}var Fp="posthog-node";function ew(r,{organization:e,projectId:t,prefix:n,severityAllowList:s=["error"],sendExceptionsToPostHog:i=!0}={}){return o=>{if(!(s==="*"||s.includes(o.level)))return o;o.tags||(o.tags={});let c=o.tags[tc.POSTHOG_ID_TAG];if(c===void 0)return o;let l=r.options.host??"https://us.i.posthog.com",u=new URL(`/project/${r.apiKey}/person/${c}`,l).toString();o.tags["PostHog Person URL"]=u;let d=o.exception?.values||[],g=d.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(_=>({..._,platform:"node:javascript"}))}:void 0})),p={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:g,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags},m=q.getInjectedReleaseId();return m&&(p.$release_id=m),e&&t&&(p.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+o.event_id),i&&r.capture({event:"$exception",distinctId:c,properties:p}),o}}var tc=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,n,s,i){this.name=Fp,this.name=Fp,this.setupOnce=function(o,a){let c=a()?.getClient()?.getDsn()?.projectId;o(ew(e,{organization:t,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:i??!0}))}}};var bi=class extends _i{getLibraryId(){return"posthog-node"}compressPayload(e){return Lp(e,this.isDebug)}initializeContext(){return new Ei}initializeSpanContextManager(){return new Si}hostResourceAttributes(){return Np()}createErrorPropertiesBuilder(){return new q.ErrorPropertiesBuilder([new q.EventCoercer,new q.ErrorCoercer,new q.ObjectCoercer,new q.StringCoercer,new q.PrimitiveCoercer],q.createStackParser("node:javascript",q.nodeStackLineParser),[Ad(),e=>cp(e,void 0,this._logger),fp()])}};var Je=new Map,ct=null,dn=new Map,Ce=null,Ie=null,tw=300*1e3,rw=3600*1e3,nw=1e3;function Up(r,e){let{records:t,windowStartTs:n,windowSeq:s}=r,i=t.length,o=0,a=0,c=0,l=0,u=0,d=0,g=0,p=0,m=0,h=0,_=0,E=0,y=0,w=0,R=0,P=0,O=0,S=0,T=new Map,b=new Map,C,Ii,uc,dc;for(let A of t)typeof A.tokens_input=="number"&&Number.isFinite(A.tokens_input)&&(o+=A.tokens_input),typeof A.tokens_output=="number"&&Number.isFinite(A.tokens_output)&&(a+=A.tokens_output),typeof A.cost_usd=="number"&&Number.isFinite(A.cost_usd)&&(c+=A.cost_usd),typeof A.duration_ms=="number"&&Number.isFinite(A.duration_ms)&&(l+=A.duration_ms,u++),typeof A.compression_ms=="number"&&Number.isFinite(A.compression_ms)&&(d+=A.compression_ms,g++),A.outcome==="ok"?p++:A.outcome==="error"?m++:A.outcome==="aborted"?(h++,A.abort_reason==="deadline_exceeded"&&_++):A.outcome==="invalid_output"&&E++,typeof A.abort_reason=="string"&&A.abort_reason&&b.set(A.abort_reason,(b.get(A.abort_reason)??0)+1),typeof A.model=="string"&&A.model&&T.set(A.model,(T.get(A.model)??0)+1),typeof A.ide=="string"&&A.ide&&(C=A.ide),typeof A.provider=="string"&&A.provider&&(Ii=A.provider),typeof A.observed_model=="string"&&A.observed_model&&(uc=A.observed_model),typeof A.observed_billing=="string"&&A.observed_billing&&(dc=A.observed_billing),typeof A.count=="number"&&Number.isFinite(A.count)&&(y+=A.count),typeof A.obs_type_bugfix=="number"&&Number.isFinite(A.obs_type_bugfix)&&(w+=A.obs_type_bugfix),typeof A.obs_type_discovery=="number"&&Number.isFinite(A.obs_type_discovery)&&(R+=A.obs_type_discovery),typeof A.obs_type_decision=="number"&&Number.isFinite(A.obs_type_decision)&&(P+=A.obs_type_decision),typeof A.obs_type_refactor=="number"&&Number.isFinite(A.obs_type_refactor)&&(O+=A.obs_type_refactor),typeof A.obs_type_other=="number"&&Number.isFinite(A.obs_type_other)&&(S+=A.obs_type_other);let lt={count:i,total_tokens_input:o,total_tokens_output:a,total_cost_usd:c,avg_duration_ms:u>0?l/u:0,avg_compression_ms:g>0?d/g:0,outcomes_ok:p,outcomes_error:m,outcomes_aborted:h,outcomes_aborted_deadline_exceeded:_,outcomes_invalid_output:E,observations_created:y,obs_type_bugfix:w,obs_type_discovery:R,obs_type_decision:P,obs_type_refactor:O,obs_type_other:S,window_start_ts:n,rollup_reason:e,window_seq:s};if(T.size>0){let A="",or=0;for(let[Pi,ar]of T)ar>or&&(or=ar,A=Pi);lt.top_model=A}if(b.size>0){let A="",or=0;for(let[Pi,ar]of b)ar>or&&(or=ar,A=Pi);lt.top_abort_reason=A}return C&&(lt.ide=C),Ii&&(lt.provider=Ii),lt.observed_model=uc??"unknown",lt.observed_billing=dc??"unknown",lt}function sw(r){let{records:e,windowStartTs:t}=r,n=e.length,s=0,i=0,o=0,a=0,c=0,l=0;for(let u of e){let d=u.tokens_injected;typeof d=="number"&&Number.isFinite(d)&&(s+=d,i++),typeof u.observation_count=="number"&&Number.isFinite(u.observation_count)&&(c+=u.observation_count),typeof u.tokens_saved_vs_naive=="number"&&Number.isFinite(u.tokens_saved_vs_naive)&&(l+=u.tokens_saved_vs_naive),u.outcome==="ok"?o++:u.outcome==="error"&&a++}return{count:n,total_tokens:s,avg_tokens:i>0?s/i:0,total_observations_injected:c,total_tokens_saved_vs_naive:l,outcomes_ok:o,outcomes_error:a,window_start_ts:t}}var It={record(r,e,t){let n=Date.now();if(r==="work_state_usage"){let s={platform:t.platform,agent_role:t.agent_role,instruction_state:t.instruction_state},i=JSON.stringify(s),o=dn.get(i)??{...s,window_start_ts:n};for(let[a,c]of Object.entries(t))a.endsWith("_count")&&typeof c=="number"&&Number.isFinite(c)&&c>=0&&(o[a]=Number(o[a]??0)+c);dn.set(i,o)}else if(r==="session_compressed"){if(typeof e!="number")return;let s=Je.get(e);s||(s={records:[],windowStartTs:n,windowSeq:0},Je.set(e,s)),s.records.push(t)}else ct||(ct={records:[],windowStartTs:n}),ct.records.push(t)},flushSession(r,e){let t=Je.get(r);if(!t||t.records.length===0)return Je.delete(r),!1;let n=Up(t,e);return Je.delete(r),Ct("observer_turn_rollup",n),!0},drainAllSessions(r){for(let e of Array.from(Je.keys()))It.flushSession(e,r)},safetyFlush(){let r=Date.now();for(let[e,t]of Array.from(Je.entries())){let n=r-t.windowStartTs>=rw,s=t.records.length>=nw;if(!n&&!s||t.records.length===0)continue;let i=Up(t,"safety_flush");Ct("observer_turn_rollup",i),t.records=[],t.windowStartTs=r,t.windowSeq+=1}},flush(){for(let r of dn.values())Ct("work_state_usage_rollup",r);if(dn.clear(),ct&&ct.records.length>0){let r=sw(ct);ct=null,Ct("context_injected_rollup",r)}},start(r=300*1e3){Ce===null&&(Ce=setInterval(()=>{It.flush()},r),Ce&&typeof Ce.unref=="function"&&Ce.unref()),Ie===null&&(Ie=setInterval(()=>{It.safetyFlush()},tw),Ie&&typeof Ie.unref=="function"&&Ie.unref())},stop(){Ce!==null&&(clearInterval(Ce),Ce=null),Ie!==null&&(clearInterval(Ie),Ie=null)},__resetForTests(){Ce!==null&&(clearInterval(Ce),Ce=null),Ie!==null&&(clearInterval(Ie),Ie=null),Je.clear(),ct=null,dn.clear()},__activeSessionBucketCount(){return Je.size}};M();var rc=null,iw=!1,ow=3e4,wi=null;function nc(){let r=Date.now();if(wi&&r<wi.expiresAt)return wi.value;let e=Nn(process.env,hr());return wi={value:e,expiresAt:r+ow},e}function Bp(){return nc()}var aw=!1;function cw(){if(!rc){let r=aw&&dl(process.env)&&nc();rc=new bi($n(),{host:Bn(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:r,before_send:_w})}return rc}var lw=6e4,uw=500,fn=new Map;function dw(r,e,t){let n="";try{let s=(t||"").split(`
33
+ `).map(i=>i.trim()).filter(Boolean);n=s.find(i=>i.startsWith("at "))??s[1]??""}catch(s){let i=s instanceof Error?s:new Error(String(s));f.warn("SYSTEM","Telemetry: stack parse failed while fingerprinting; using empty top frame",void 0,i),n=""}return`${r}::${_l(e)}::${n}`.slice(0,400)}function fw(r,e){try{return pw(r,e)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: error rate-limit bookkeeping failed; failing closed (event dropped)",void 0,n),{send:!1,count:0}}}function pw(r,e){let t=fn.get(r);if(!t){if(fn.size>=uw){let n=null,s=1/0;for(let[i,o]of fn){let a=Math.max(o.lastSentTs,o.firstTs);a<s&&(s=a,n=i)}n!==null&&fn.delete(n)}return t={count:1,firstTs:e,lastSentTs:e},fn.set(r,t),{send:!0,count:1}}if(t.count+=1,e-t.lastSentTs>=lw){t.lastSentTs=e;let n=t.count;return t.count=0,{send:!0,count:n}}return{send:!1,count:t.count}}var $p="__cm_rate_limited";function gw(r){try{return typeof r!="string"||r.length===0?"":to(eo(r))}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: frame filename redaction failed; stripping value entirely",void 0,t),""}}function mw(r){let e=r.$exception_list;if(Array.isArray(e))for(let t of e){if(!t||typeof t!="object")continue;let n=t;typeof n.value=="string"&&(n.value=hl(n.value));let i=n.stacktrace?.frames;if(Array.isArray(i))for(let o of i){if(!o||typeof o!="object")continue;let a=o;delete a.context_line,delete a.pre_context,delete a.post_context,typeof a.filename=="string"&&(a.filename=gw(a.filename))}}}function hw(r){try{let e=[],t=i=>{typeof i=="string"&&e.push(i)};t(r.$exception_message),t(r.$exception_type),t(r.error_message),t(r.error_type);let n=r.$exception_list;if(Array.isArray(n))for(let i of n)i&&typeof i=="object"&&(t(i.value),t(i.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 _w(r){try{if(!r||typeof r!="object")return r;let e=r;if(e.event!=="$exception")return r;let t=e.properties??{};if(hw(t))return null;if(t[$p]){try{delete t[$p],e.properties=t}catch{}return r}mw(t),t.$process_person_profile=!1,e.properties=t;let n="Error",s="",i="";try{let c=t.$exception_list;if(Array.isArray(c)&&c[0]&&typeof c[0]=="object"){let l=c[0];typeof l.type=="string"&&(n=l.type),typeof l.value=="string"&&(s=l.value);let u=l.stacktrace?.frames;Array.isArray(u)&&u.length>0&&(i="at "+JSON.stringify(u[u.length-1]).slice(0,200))}}catch{}typeof t.$exception_type=="string"&&(n=t.$exception_type),typeof t.$exception_message=="string"&&(s=t.$exception_message);let o=dw(n,s,i),a=fw(o,Date.now());if(!a.send)return null;try{t.occurrence_count=a.count,e.properties=t}catch{}return r}catch{return null}}function Ct(r,e,t){try{Ew(r,e,t)}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","Telemetry: captureEvent failed; event dropped",{event:r},s)}}function Ew(r,e,t){if(iw||!nc())return;let n=Un({...Hn(),...e??{}});if(t?.person?n.$set=Wn(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
34
+ `);return}cw().capture({distinctId:Fn(),event:r,properties:n})}var Sw=["agent-cost-report","babysit","build","build-and-release","ccs-align","childhood","cloud-sync","design-is","do","handoff","how-it-works","knowledge-agent","learn-codebase","make-plan","mem-search","mode-creator","oh-my-issues","pathfinder","release","screenpipe","smart-explore","standup","timeline-report","version-bump","weekly-digests","what-the","wowerpoint"],yw=new Set(Sw),Wp={skill_id:"other",skill_source:"third_party"};function Hp(r){let e=bw(r);return e&&yw.has(e)?{skill_id:e,skill_source:"first_party"}:Wp}function jp(r,e){if(r==="Skill"&&!(!e||typeof e!="object"))return e.skill}function bw(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();if(!e)return null;e=e.replace(/^\/+/,"");let t=e.lastIndexOf(":");return t!==-1&&(e=e.slice(t+1).replace(/^\/+/,"")),e||null}var ww=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 Kp(r){if(!r.startsWith("mcp__"))return null;let e=r.split("__");if(e.length<3)return null;let t=e[1].toLowerCase();return!t.includes("claude-mem")&&!t.includes("claude_mem")&&!t.includes("mcp-search")&&!t.includes("mcp_search")&&!t.includes("cmem")?null:e.slice(2).join("__")}function Gp(r){if(!r)return!1;if(r.startsWith("memory_")||r==="mem_search"||r==="get_summaries")return!0;let e=Kp(r);return e!==null&&ww.has(e)}function zp(r){return r==="save_memory"||Kp(r)==="save_memory"}var qp=require("crypto");var Ti=new WeakMap,Yp=720*60*60*1e3,Jp=(...r)=>(0,qp.createHash)("sha256").update(r.join("\0")).digest("hex");function Tw(r){Ti.has(r)||(r.run("CREATE TABLE IF NOT EXISTS work_state_telemetry_receipts (key TEXT PRIMARY KEY, state TEXT, created_at_epoch INTEGER NOT NULL DEFAULT 0)"),r.query("PRAGMA table_info(work_state_telemetry_receipts)").all().some(n=>n.name==="created_at_epoch")||r.run("ALTER TABLE work_state_telemetry_receipts ADD COLUMN created_at_epoch INTEGER NOT NULL DEFAULT 0"),r.run("CREATE INDEX IF NOT EXISTS idx_work_state_telemetry_age ON work_state_telemetry_receipts(created_at_epoch)"),Ti.set(r,0));let e=Date.now();e-Ti.get(r)>=3600*1e3&&(r.query("DELETE FROM work_state_telemetry_receipts WHERE created_at_epoch < ?").run(e-Yp),Ti.set(r,e))}function Xp(r){return Bp()?(Tw(r),!0):!1}function Qp(r){return Jp(wr(r.platformSource),r.contentSessionId,r.agentId??"")}function Aw(r,e){let t=r.query("SELECT state FROM work_state_telemetry_receipts WHERE key = ?").get(`instruction:${Qp(e)}`);if(!t?.state)return null;try{let n=JSON.parse(t.state);return n&&["returned","disabled","excluded","missing","unknown"].includes(n.state)&&Number.isFinite(n.at)?n:null}catch{return null}}function Vp(r,e){let t=Aw(r,e),n=t&&Number.isFinite(e.enqueuedAtEpochMs)&&t.at<=e.enqueuedAtEpochMs?t.state:"unknown";return{platform:wr(e.platformSource),agent_role:e.agentRole??(vs(e.agentId,e.agentType)?"subagent":e.agentId||e.agentType?"main":"unknown"),instruction_state:n}}function Rw(r,e){return r.query("INSERT OR IGNORE INTO work_state_telemetry_receipts (key, created_at_epoch) VALUES (?, ?)").run(e,Date.now()).changes>0}function Zp(r){return typeof r=="number"&&Number.isFinite(r)&&r>=Date.now()-Yp}function sc(r,e){try{if(!Xp(r)||!Zp(e.enqueuedAtEpochMs))return!1;let t=r.query("SELECT state FROM work_state_telemetry_receipts WHERE key = ?").get(`privacy:${Qp(e)}`);if(!t?.state)return!1;let n=JSON.parse(t.state);return n.private===!1&&Number.isFinite(n.at)&&n.at<=e.enqueuedAtEpochMs}catch{return!1}}function vw(r){try{r()}catch{}}function ic(r,e,t,n,s){vw(()=>{if(!Xp(r)||!Zp(e.enqueuedAtEpochMs))return;if(!t){It.record("work_state_usage",null,{...Vp(r,e),unidentified_tool_event_count:1});return}if(!Rw(r,`tool:${Jp(e.contentSessionId,t)}`))return;let i=ls(n);It.record("work_state_usage",null,{...Vp(r,e),captured_tool_count:1,...i==="native_todo"?{native_todo_count:1}:i?{[`captured_${i}_count`]:1,[`captured_${i}_${Bo(i,s)}_count`]:1}:{}})})}var eg=null,Mw=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),tg=new Map;function Ow(r){let e=tg.get(r);if(e!==void 0)return e;let t=null;try{t=new RegExp(r)}catch(n){f.warn("INGEST","Invalid CLAUDE_MEM_SKIP_BASH_PATTERNS regex \u2014 ignoring",{pattern:r,error:n instanceof Error?n.message:String(n)})}return tg.set(r,t),t}function Cw(r,e){if(!e||typeof e!="object")return"";let t=e,n=r==="Bash"||r==="PowerShell"?t.command:r==="exec_command"?t.cmd:void 0;return typeof n=="string"?n:""}function Iw(){if(!eg)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return eg}async function rg(r,e={}){if(Gp(r.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};let{sessionManager:t,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:i}=Iw(),o=V(r.platformSource),a=typeof r.cwd=="string"?r.cwd:"",c=a.trim()?mt(a):null,l=c?.primary||"unknown",u=H.loadFromFile(ne);if(a&&Kn(a,u.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};let d=ls(r.toolName),g={...r,platformSource:r.telemetryPlatformSource??r.platformSource,enqueuedAtEpochMs:r.telemetryToolEpochMs??r.enqueuedAtEpochMs};if(d&&!Jo(r.agentId,r.agentType,u).skip)try{let S=n.getSessionStore(),T=S.findSessionDbIdByContentSessionId(r.contentSessionId,o),b=S.getPromptNumberFromUserPrompts(r.contentSessionId,T??void 0,r.enqueuedAtEpochMs);(T===null?null:S.getUserPrompt(r.contentSessionId,b,T))?.trim()&&sc(S.db,g)&&ic(S.db,g,r.toolUseId,r.toolName,r.toolResponse)}catch{}if(As(r.toolName,u.CLAUDE_MEM_SKIP_TOOLS)){if(r.toolName==="Skill"){let{skill_id:S,skill_source:T}=Hp(jp(r.toolName,r.toolInput));Ct("skill_invoked",{skill_id:S,skill_source:T,skill_trigger:"tool",ide:o})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(o==="kimi"&&Mw.has(r.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let p=u.CLAUDE_MEM_SKIP_BASH_PATTERNS.trim(),m=p?Cw(r.toolName,r.toolInput):"";if(m){let S=Ow(p);if(S&&S.test(m))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let h=Jo(r.agentId,r.agentType,u);if(h.skip)return{ok:!0,status:"skipped",reason:h.reason};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let S=r.toolInput,T=S.file_path||S.notebook_path;if(T&&T.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let E=n.getSessionStore(),y,w;try{y=E.createSDKSession(r.contentSessionId,l,"",void 0,o),a&&E.setSessionCwd(y,a,c?.keySource),w=E.getPromptNumberFromUserPrompts(r.contentSessionId,y,r.enqueuedAtEpochMs)}catch(S){let T=S instanceof Error?S.message:String(S);return f.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},S instanceof Error?S:new Error(T)),{ok:!1,reason:T,status:500}}let R=Ms.checkUserPromptPrivacy(E,r.contentSessionId,w,"observation",y,{tool_name:r.toolName});if(!R.allow)return{ok:!0,status:"skipped",reason:"private"};!d&&R.prompt.trim()&&sc(E.db,g)&&ic(E.db,g,r.toolUseId,r.toolName,r.toolResponse);let P=r.toolInput!==void 0?ps(JSON.stringify(r.toolInput)):"{}",O=r.toolResponse!==void 0?ps(JSON.stringify(r.toolResponse)):"{}";if(r.toolUseId)try{E.upsertToolUse({toolUseId:r.toolUseId,contentSessionId:r.contentSessionId,sessionDbId:y,project:l,platformSource:o,toolName:r.toolName,toolInput:P,toolResponse:O,cwd:a||null,promptNumber:w,agentType:typeof r.agentType=="string"?r.agentType:null,agentId:typeof r.agentId=="string"?r.agentId:null,orGenerationId:typeof r.orGenerationId=="string"?r.orGenerationId:null,orSessionId:typeof r.orSessionId=="string"?r.orSessionId:null})}catch(S){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:y,toolName:r.toolName,toolUseId:r.toolUseId},S instanceof Error?S:new Error(String(S)))}return zp(r.toolName)?{ok:!0,status:"skipped",reason:"explicit_memory_write"}:(t.queueObservation(y,{tool_name:r.toolName,tool_input:P,tool_response:O,prompt_number:w,cwd:a||(f.error("INGEST","Missing cwd when ingesting observation",{sessionId:y,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0},r.enqueuedAtEpochMs),e.markHandedOff?.(),await i?.(y,"observation"),s.broadcastObservationQueued(y),{ok:!0,sessionDbId:y})}var Pw=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function kw(r){let e=typeof r.agentId=="string"?r.agentId.trim():"";return e&&e!=="*"?e:r.path.match(Pw)?.[1]}var gn=class extends Error{constructor(e,t){super(`session init failed for transcript session ${e}: ${t instanceof Error?t.message:String(t)}`),this.name="TranscriptAnchorError",this.cause=t}},mn=class extends Error{constructor(e,t){super(`observation not accepted for transcript session ${e}: ${t instanceof Error?t.message:String(t)}`),this.name="TranscriptObservationError",this.cause=t}},Pt=class extends Error{constructor(e,t){super(`transcript event not persisted for session ${e}: ${t instanceof Error?t.message:String(t)}`),this.name="TranscriptSpoolError",this.cause=t}},xw=4096,Dw=64,Ai=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 t of this.sessionKeysOf(e)){let n=this.sessions.get(t);n&&n.cwd===e.cwd&&(n.cwd=void 0)}this.retireFileContext(e),e.cwd=void 0,e.sessionId=void 0}retireFileContext(e){for(let t of this.sessionKeysOf(e)){let n=this.sessions.get(t)?.pendingTools;for(let[s,i]of n??[])this.pendingToolOwners.get(i)===e&&n.delete(s)}this.fileContexts.delete(e),this.fileSessionKeys.delete(e),e.pendingTools={}}sessionKeysOf(e){return new Set([...Object.keys(e.pendingTools??{}),...this.fileSessionKeys.get(e)??[]])}async processEntry(e,t,n,s,i){i&&this.registerFileContext(i);for(let o of n.events)kr(e,o.match,n)&&await this.handleEvent(e,t,n,o,s??void 0,i)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),s=this.sessions.get(n);return s||(s={sessionId:t,platformSource:V(e.name),...this.subagentSessionKeys.has(n)?{isSubagent:!0}:{}},this.sessions.set(n,s)),s}rememberSubagentSession(e){if(this.subagentSessionKeys.delete(e),this.subagentSessionKeys.add(e),this.subagentSessionKeys.size>xw){let t=this.subagentSessionKeys.values().next().value;t!==void 0&&this.subagentSessionKeys.delete(t)}}async primeSessionContext(e,t,n,s,i){for(let o of n.events)o.action!=="session_context"||!kr(e,o.match,n)||await this.handleEvent(e,t,n,o,s??void 0,i)}resolveSessionId(e,t,n,s,i){let o={watch:t,schema:n},a=s.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=Kt(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):i&&i.trim()?i:null}resolveCwd(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=Kt(a,e,o);return typeof c=="string"&&c.trim()?c:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=Kt(a,e,o);return typeof c=="string"&&c.trim()?c:t.project?t.project:i.cwd?mt(i.cwd).primary:i.project}async handleEvent(e,t,n,s,i,o){let a=this.resolveSessionId(e,t,n,s,o?.sessionId??i);if(!a){f.debug("TRANSCRIPT","Skipping event without sessionId",{event:s.name,watch:t.name});return}o&&(o.sessionId=a);let c=this.getOrCreateSession(t,a),l=this.getSessionKey(t,a);if(o){let p=this.fileSessionKeys.get(o)??new Set;p.add(l),this.fileSessionKeys.set(o,p)}if(o?.pendingTools?.[l]){c.pendingTools??=new Map;for(let[p,m]of Object.entries(o.pendingTools[l]))this.pendingToolOwners.set(m,o),c.pendingTools.has(p)||c.pendingTools.set(p,m)}!c.cwd&&o?.cwd&&(c.cwd=o.cwd);let u=this.resolveCwd(e,t,n,s,c);u&&(c.cwd=u);let d=this.resolveProject(e,t,n,s,c);if(d&&(c.project=d),t.subagentSource&&!c.isSubagent){let p=Pr(e,t.subagentSource.path);p!=null&&(c.isSubagent=!0,this.rememberSubagentSession(this.getSessionKey(t,a)))}if(t.subagentOnly&&!c.isSubagent&&s.action!=="session_context"&&s.action!=="session_end")return;let g=bd(s.fields,e,{watch:t,schema:n,session:c});s.action==="session_context"&&this.applySessionContext(c,g),o&&c.cwd&&(o.cwd=c.cwd);try{switch(s.action){case"session_context":break;case"session_init":await this.handleSessionInit(c,g),t.context?.updateOn?.includes("session_start")&&await this.updateContext(c,t);break;case"user_message":{let p=this.resolveMessageText(g.message)??this.resolveMessageText(g.prompt);p&&await this.anchorUserPrompt(c,p);break}case"assistant_message":c.lastAssistantMessage=this.resolveMessageText(g.message)??c.lastAssistantMessage;break;case"tool_use":await this.handleToolUse(c,t,g,o);break;case"tool_result":await this.handleToolResult(c,t,g,o);break;case"observation":await this.sendObservation(c,t,g);break;case"file_edit":await this.sendFileEdit(c,g);break;case"session_end":await this.handleSessionEnd(c,t);break;default:break}}finally{o&&this.snapshotPendingTools(o,c,l,s.action==="session_end")}}snapshotPendingTools(e,t,n,s){let i=s?{}:{...e.pendingTools?.[n]};for(let[a,c]of t.pendingTools??[])this.pendingToolOwners.get(c)===e&&(i[a]=c);e.pendingTools={...e.pendingTools,[n]:i},Object.keys(i).length===0&&delete e.pendingTools[n];let o=Object.entries(e.pendingTools).flatMap(([a,c])=>Object.keys(c).map(l=>[a,l]));for(let[a,c]of o.slice(0,Math.max(0,o.length-Dw))){let l=e.pendingTools[a],u=l[c];delete l[c],Object.keys(l).length===0&&delete e.pendingTools[a];let d=this.sessions.get(a)?.pendingTools;d?.get(c)===u&&d.delete(c)}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,s=typeof t.project=="string"?t.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 t=[];for(let n of e)n&&typeof n=="object"&&typeof n.text=="string"&&t.push(n.text);return t.length>0?t.join(`
35
+ `):void 0}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"";await this.anchorUserPrompt(e,n)}async anchorUserPrompt(e,t){t&&(e.lastUserMessage=t);let n=e.cwd;if(!n){this.skipWithoutCwd(e,"user prompt");return}try{await rd({sessionId:e.sessionId,cwd:n,prompt:t,platform:e.platformSource})}catch(s){throw new gn(e.sessionId,s)}}skipWithoutCwd(e,t){f.debug("TRANSCRIPT",`Skipping a ${t}: the session has no known working directory yet`,{sessionId:e.sessionId})}async handleToolUse(e,t,n,s){let i=typeof n.toolId=="string"?n.toolId:void 0,o=typeof n.toolName=="string"?n.toolName:void 0,a=this.maybeParseJson(n.toolInput),c=this.maybeParseJson(n.toolResponse);if(o==="apply_patch"&&typeof a=="string"){let l=this.parseApplyPatchFiles(a);for(let u of l)await this.sendFileEdit(e,{filePath:u,edits:[{type:"apply_patch",patch:a}]})}if(o&&c!==void 0)await this.sendObservation(e,t,{toolName:o,toolInput:a,toolResponse:c,toolUseId:i});else if(o&&i){e.pendingTools||(e.pendingTools=new Map);let l={toolName:o,toolInput:a};s&&this.pendingToolOwners.set(l,s),e.pendingTools.set(i,l)}}async handleToolResult(e,t,n,s){let i=typeof n.toolId=="string"?n.toolId:void 0,o=typeof n.toolName=="string"?n.toolName:void 0,a=this.maybeParseJson(n.toolResponse),c=this.maybeParseJson(n.toolInput),l=s?.pendingTools?.[this.getSessionKey(t,e.sessionId)],u=i?e.pendingTools?.get(i):void 0,d=s,g=s?(i?l?.[i]:void 0)??(u&&this.pendingToolOwners.get(u)===s?u:void 0):u;if(!g&&s&&i){let p=Array.from(this.fileContexts).flatMap(m=>{let h=m.pendingTools?.[this.getSessionKey(t,e.sessionId)]?.[i];return h&&m.isCurrent?.()!==!1?[{context:m,tool:h}]:[]});p.length===1&&(d=p[0].context,g=p[0].tool)}if(g&&(o||(o=g.toolName),c===void 0&&(c=g.toolInput)),o){if(await this.sendObservation(e,t,{toolName:o,toolInput:c,toolResponse:a,toolUseId:i}),i){e.pendingTools&&e.pendingTools.get(i)===g&&e.pendingTools.delete(i);let p=d?.pendingTools?.[this.getSessionKey(t,e.sessionId)];p&&delete p[i]}}else f.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:i})}async sendObservation(e,t,n){let s=typeof n.toolName=="string"?n.toolName:void 0;if(!s)return;if(!e.cwd){this.skipWithoutCwd(e,"observation");return}let i={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:kw(t)};if(this.observationTransport==="spool"){try{Or("observation",i)}catch(a){throw new Pt(e.sessionId,a)}return}let o=!1;try{let a=await rg(i,{markHandedOff:()=>{o=!0}});if(!a.ok)throw new Error(a.reason)}catch(a){if(o){f.warn("TRANSCRIPT","Observation accepted before generator kick failed",{sessionId:e.sessionId},a instanceof Error?a:void 0);return}throw new mn(e.sessionId,a)}}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;if(n){if(!e.cwd){this.skipWithoutCwd(e,"file edit");return}try{await md.execute({sessionId:e.sessionId,cwd:e.cwd,filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}catch(s){throw new Pt(e.sessionId,s)}}}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return f.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
36
+ `);for(let s of n){let i=s.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let o=i.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&t.push(o)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){(!t.subagentOnly||e.isSubagent)&&(await this.queueSummary(e),await this.updateContext(e,t)),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(this.observationTransport==="spool"){try{Or("summarize",{contentSessionId:e.sessionId,platformSource:e.platformSource,lastAssistantMessage:e.lastAssistantMessage??"",...e.cwd?{cwd:e.cwd}:{}})}catch(i){throw new Pt(e.sessionId,i)}return}if(!await is())return;let n=e.lastAssistantMessage??"",s=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource,...e.cwd?{cwd:e.cwd}:{}});try{await Fe("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:s})}catch(i){f.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||xc(t)||!await is())return;let s=e.cwd??t.workspace;if(!s)return;let o=mt(s).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=ie(t.context.path??`${s}/AGENTS.md`),l=pn.default.resolve(c),u=[pn.default.resolve(s),pn.default.resolve(U)];if(!u.some(m=>l.startsWith(m+pn.default.sep)||l===m)){f.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:l,allowedRoots:u});return}let g;try{g=await Fe(a)}catch(m){f.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:m instanceof Error?m.message:String(m)});return}if(!g.ok)return;let p=(await g.text()).trim();p&&(Ed(c,p),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:t.name}))}};var ng=me(require("node:zlib"),1),ir=require("node:fs");M();function sg(){let r=ng.zstdDecompressSync;return typeof r=="function"?r:void 0}function ig(){return sg()!==void 0}var Lw=4247762216,Nw=64*1024;function Ri(r,e,t,n=Number.POSITIVE_INFINITY){let s=(0,ir.openSync)(r,"r");try{let i=Buffer.alloc(0),o=0,a=(u,d)=>{if(u+d>t)return null;if(u<o||u+d>o+i.length){let g=Math.min(Math.max(d,Nw),t-u),p=Buffer.alloc(g);if(i=p.subarray(0,(0,ir.readSync)(s,p,0,g,u)),o=u,i.length<d)return null}return i.subarray(u-o,u-o+d)},c=[],l=e;for(;l<t&&(c.length===0||l-e<n);){let u=l,d=a(l,4);if(!d)return{frames:c,tornStart:u};if(d.readUInt32LE(0)!==Lw)throw new Error(`invalid Zstandard frame magic at byte ${l}`);l+=4;let g=a(l,1);if(!g)return{frames:c,tornStart:u};let p=g.readUInt8(0);if(l+=1,(p&8)!==0)throw new Error(`reserved Zstandard frame-header bit at byte ${l-1}`);let m=p>>>6,h=(p&32)!==0,_=(p&4)!==0,E=p&3,y=E===3?4:E,w=m===0?h?1:0:1<<m,R=(h?0:1)+y+w;if(l+R>t)return{frames:c,tornStart:u};for(l+=R;;){let P=a(l,3);if(!P)return{frames:c,tornStart:u};let O=P.readUIntLE(0,3);l+=3;let S=(O&1)!==0,T=O>>>1&3,b=O>>>3;if(T===3)throw new Error(`reserved Zstandard block type at byte ${l-3}`);let C=T===1?1:b;if(l+C>t)return{frames:c,tornStart:u};if(l+=C,S)break}if(_){if(l+4>t)return{frames:c,tornStart:u};l+=4}c.push({start:u,end:l})}return{frames:c,tornStart:null}}finally{(0,ir.closeSync)(s)}}function oc(r,e){try{let t=sg();if(!t)throw new Error("this runtime cannot decode Zstandard (zlib.zstdDecompressSync is missing)");return t(r.subarray(e.start,e.end))}catch(t){throw f.warn("TRANSCRIPT","Failed to decompress Zstandard frame",{start:e.start,end:e.end,error:t instanceof Error?t.message:String(t)}),t}}function og(r,e){return oc(r,e).toString("utf8")}var ag=2e3,Fw=1e3,Uw=256*1024,cg=4*1024*1024,$w=16*1024*1024,Bw=100,lg=100;function hn(){return new Promise(r=>setImmediate(r))}var vi=".jsonl.zstd";async function Ww(r,e){try{let t=0;for(;t<e;){let n=Ri(r,t,e,$w);if(n.tornStart!==null)return n.tornStart;if(n.frames.length===0)break;t=n.frames[n.frames.length-1].end,await hn()}return t}catch{return e}}var ug=1024*1024;async function pg(r,e,t){let n;if(e){let{frames:i}=Ri(r,0,Math.min(t,ug),1);if(i.length===0)return null;n=og(await Oi(r,0,i[0].end),i[0])}else n=(await Oi(r,0,Math.min(t,ug))).toString("utf8");let s=n.indexOf(`
37
+ `);return s<0?null:n.slice(0,s)}async function Hw(r,e,t){try{let n=await pg(r,e,t);if(n===null)return null;let s=JSON.parse(n);for(let i of["timestamp","time","createdAt"]){let o=s?.[i],a=typeof o=="number"?o<1e12?o*1e3:o:typeof o=="string"?Date.parse(o):Number.NaN;if(Number.isFinite(a)&&a>0)return a}return null}catch{return null}}function Mi(r){return`${r.dev}:${r.ino}`}function jw(r){try{return(0,B.statSync)(r),!1}catch(e){let t=e.code;return t==="ENOENT"||t==="ENOTDIR"}}var Kw=4096;function cc(r,e,t){let n;try{if(n=(0,B.openSync)(r,"r"),Mi((0,B.fstatSync)(n))!==t)return null;let s=Math.max(0,e-Kw),i=Buffer.alloc(e-s);return(0,B.readSync)(n,i,0,i.length,s)<i.length?null:(0,dg.createHash)("sha256").update(i).digest("hex")}catch(s){return f.debug("TRANSCRIPT","Could not fingerprint a transcript checkpoint",{file:r},s instanceof Error?s:void 0),null}finally{n!==void 0&&(0,B.closeSync)(n)}}function gg(r,e,t,n,s){return t<n?!1:s===void 0?!0:cc(r,n,e)===s}async function Oi(r,e,t){let n=await(0,fg.open)(r,"r");try{let s=Buffer.alloc(t),{bytesRead:i}=await n.read(s,0,t,e);return s.subarray(0,i)}finally{await n.close()}}var ac=class{constructor(e,t,n,s,i="",o=0,a,c,l,u){this.filePath=e;this.onLine=n;this.onOffset=s;this.onReset=l;this.fileIdentity=a,this.checkpointFingerprint=c,this.isZstd=e.endsWith(vi),this.zstdPartialBytes=this.isZstd&&u?Buffer.from(u,"base64"):void 0,this.tailState={offset:t,readOffset:t,partial:this.isZstd?i:""},this.frameLinesDone=this.isZstd?o:0}filePath;onLine;onOffset;onReset;watcher=null;tailState;readTask=null;readPending=!1;closed=!1;isZstd;pendingRecord=Buffer.alloc(0);frameLinesDone;zstdPartialBytes;fileIdentity;checkpointFingerprint;start(){this.requestRead();try{this.watcher=(0,B.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})}}async drainReads(){do this.readPending=!1,await this.readNewData().catch(()=>{}),this.readPending&&await hn();while(this.readPending&&!this.closed)}async readNewData(){if(!(0,B.existsSync)(this.filePath))return;let e=0,t;try{let o=(0,B.statSync)(this.filePath);e=o.size,t=Mi(o)}catch(o){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}let n=t!==this.fileIdentity,s=!1;n&&this.fileIdentity!==void 0&&(gg(this.filePath,t,e,this.tailState.offset,this.checkpointFingerprint)?(this.tailState.readOffset=this.tailState.offset,this.pendingRecord=Buffer.alloc(0)):s=!0),this.fileIdentity=t;let i=s||e<this.tailState.readOffset;if(i&&(this.onReset?.(),this.tailState.offset=0,this.tailState.readOffset=0,this.tailState.partial="",this.zstdPartialBytes=void 0,this.pendingRecord=Buffer.alloc(0),this.frameLinesDone=0),e===this.tailState.readOffset){(n||i)&&this.checkpoint(this.tailState.offset,this.tailState.partial);return}this.isZstd?await this.readNewZstdFrames(e):await this.readNewJsonl(e)}checkpoint(e,t="",n=this.zstdPartialBytes){this.zstdPartialBytes=n,this.tailState.offset=e,this.tailState.partial=t,this.checkpointFingerprint=this.fileIdentity===void 0?void 0:cc(this.filePath,e,this.fileIdentity)??void 0,this.onOffset(e,t,this.frameLinesDone,this.fileIdentity,this.checkpointFingerprint,this.zstdPartialBytes?.toString("base64"))}async readNewJsonl(e){let t=this.tailState.readOffset,n;try{n=await Oi(this.filePath,t,Math.min(e-t,cg))}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=t+n.length;let s=this.pendingRecord.length>0?Buffer.concat([this.pendingRecord,n]):n,i=this.tailState.offset,o=0,a=0;for(let c=s.indexOf(10);c!==-1;c=s.indexOf(10,o)){if(this.closed){this.checkpoint(i+o);return}let l=s.toString("utf8",o,c).trim();if(l)try{await this.onLine(l)}catch{this.pendingRecord=Buffer.alloc(0),this.tailState.readOffset=i+o,this.checkpoint(i+o);return}o=c+1,this.tailState.offset=i+o,l&&++a%lg===0&&(this.checkpoint(this.tailState.offset),await hn())}this.pendingRecord=Buffer.from(s.subarray(o)),this.checkpoint(i+o),this.tailState.readOffset<e&&(this.readPending=!0)}async readNewZstdFrames(e){let t=this.tailState.offset,n,s;try{if(n=Ri(this.filePath,t,e,cg),n.frames.length===0)return;let o=n.frames[n.frames.length-1].end;if(s=await Oi(this.filePath,t,o-t),s.length<o-t)return}catch(o){f.warn("TRANSCRIPT","Failed to read zstd transcript frames",{file:this.filePath,error:o instanceof Error?o.message:String(o)});return}let i=0;for(let o of n.frames){let a;try{a=oc(s,{start:o.start-t,end:o.end-t})}catch{this.checkpoint(this.tailState.offset,this.tailState.partial);return}let c=this.tailState.partial,l=this.zstdPartialBytes,u=Buffer.concat([l??Buffer.from(c,"utf8"),a]),d=[],g=0;for(let _=u.indexOf(10);_!==-1;_=u.indexOf(10,g))d.push(u.toString("utf8",g,_)),g=_+1;let p=u.subarray(g),m=p.toString("utf8"),h=Buffer.from(m,"utf8").equals(p)?void 0:Buffer.from(p);for(let _=this.frameLinesDone;_<d.length;_++){if(this.closed){this.frameLinesDone=_,this.checkpoint(o.start,c,l);return}let E=d[_].trim();if(E){try{await this.onLine(E)}catch{this.frameLinesDone=_,this.tailState.readOffset=o.start,this.checkpoint(o.start,c,l);return}++i%lg===0&&await hn()}}this.frameLinesDone=0,this.tailState.offset=o.end,this.tailState.readOffset=o.end,this.tailState.partial=h?"":m,this.zstdPartialBytes=h}this.checkpoint(this.tailState.offset,this.tailState.partial),n.tornStart===null&&this.tailState.offset<e&&(this.readPending=!0)}},Ci=class{constructor(e,t,n="in-process"){this.config=e;this.statePath=t;this.processor=new Ai(n),this.state=Bc(t)}config;statePath;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;missingTranscriptGraceMs=Fw;rootWatchers=[];rootWatchSettleTimers=new Set;startedAtMs=0;warnedZstdUnsupported=!1;startingTailers=new Set;stopped=!1;async start(){this.stopped=!1,this.startedAtMs=Date.now();for(let e of this.config.watches)await this.setupWatch(e);if(!this.stopped)for(let e of Object.keys(this.state.pendingTools??{}))this.tailers.has(e)||this.scheduleRetirementCheck(e)}stop(){this.stopped=!0;for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[];for(let e of this.rootWatchSettleTimers)clearTimeout(e);this.rootWatchSettleTimers.clear(),this.retirementTimer&&clearTimeout(this.retirementTimer),this.retirementTimer=null,this.retirementCandidates.clear()}async setupWatch(e){let t=this.resolveSchema(e);if(!t){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=ie(e.path),s=this.resolveWatchFiles(n);for(let o of s)this.getFileContext(o);let i={stateChanged:!1};for(let o of s)await this.addTailer(o,e,t,!1,i),await hn();i.stateChanged&&gr(this.statePath,this.state),this.watchTranscriptRoot(n,e,t)}watchTranscriptRoot(e,t,n,s=!1){let i=this.selectWatchRoot(e);if(!i){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:t.name,path:e});return}let{root:o,recursive:a}=i;try{let c=(0,B.watch)(o,{recursive:a,persistent:!0},(l,u)=>{a?this.handleRootWatchEvent(o,e,t,n,u):this.handleAncestorWatchEvent(c,o,e,t,n,u)});this.rootWatchers.push(c),(s||!a)&&this.settleRootWatch(c,o,a,e,t,n),f.info("TRANSCRIPT",a?"Watching transcript root recursively":"Transcript root does not exist yet; watching its closest existing directory",{watch:t.name,watchRoot:o})}catch(c){f.warn("TRANSCRIPT","Failed to start fs.watch on transcript root",{watch:t.name,watchRoot:o},c instanceof Error?c:void 0)}}handleRootWatchEvent(e,t,n,s,i){if(!i)return;let o=(0,z.resolve)(e,i).replace(/\\/g,"/"),a=this.tailers.get(o);if(a){if(!(0,B.existsSync)(o)){a.close(),this.tailers.delete(o),this.scheduleRetirementCheck(o);return}a.poke();return}this.touchesLiteralPrefix(o,t)&&this.addDiscoveredTailers(t,n,s)}handleAncestorWatchEvent(e,t,n,s,i,o){if(this.stopped||!this.rootWatchers.includes(e)||o&&!this.touchesLiteralPrefix((0,z.resolve)(t,o),n))return;let a=this.selectWatchRoot(n);a&&a.root===t&&!a.recursive||(e.close(),this.rootWatchers=this.rootWatchers.filter(c=>c!==e),this.watchTranscriptRoot(n,s,i,!0),this.addDiscoveredTailers(n,s,i))}settleRootWatch(e,t,n,s,i,o){let a=setTimeout(()=>{this.rootWatchSettleTimers.delete(a),!(this.stopped||!this.rootWatchers.includes(e))&&(n?this.addDiscoveredTailers(s,i,o):this.handleAncestorWatchEvent(e,t,s,i,o,null))},Bw);this.rootWatchSettleTimers.add(a)}getFileContext(e){let t=this.fileContexts.get(e);return t||(t={cwd:this.state.cwds?.[e],pendingTools:this.state.pendingTools?.[e],isCurrent:()=>this.isCheckpointedFile(e)},this.fileContexts.set(e,t)),this.processor.registerFileContext(t),t}isCheckpointedFile(e){try{let t=(0,B.statSync)(e);return Mi(t)===this.state.fileIdentities?.[e]&&t.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 t=!1;for(let n of e){if(this.tailers.has(n)||!jw(n))continue;let s=this.fileContexts.get(n);s&&this.processor.retireFileContext(s),this.fileContexts.delete(n),this.state.pendingTools?.[n]&&(delete this.state.pendingTools[n],t=!0)}t&&gr(this.statePath,this.state)}forgetReplacedTranscript(e,t){this.processor.resetFileContext(t),delete this.state.pendingTools?.[e],delete this.state.cwds?.[e]}addDiscoveredTailers(e,t,n){for(let s of this.resolveWatchFiles(e))this.tailers.has(s)||this.addTailer(s,t,n,!0).catch(i=>{f.debug("TRANSCRIPT","Failed to add transcript tailer",{file:s,watch:t.name},i instanceof Error?i:void 0)})}touchesLiteralPrefix(e,t){let n=e.replace(/\\/g,"/"),s=(0,z.resolve)(this.literalWatchPrefix(t)).replace(/\\/g,"/"),i=(o,a)=>o.startsWith(a.endsWith("/")?a:a+"/");return n===s||i(n,s)||i(s,n)}literalWatchPrefix(e){let t=e;if(this.hasGlob(e)){let n=e.split(/[/\\]/),s=[];for(let i of n){if(/[*?[\]{}()]/.test(i))break;s.push(i)}if(s.length===0||s.length===1&&s[0]==="")return"";t=s.join(z.sep)}return t}selectWatchRoot(e){let t=this.literalWatchPrefix(e);if(!t)return null;let n=(0,z.resolve)(t);try{return{root:(0,B.statSync)(n).isDirectory()?n:(0,z.resolve)(n,".."),recursive:!0}}catch{}for(let s=(0,z.resolve)(n,"..");(0,z.resolve)(s,"..")!==s;s=(0,z.resolve)(s,".."))try{if((0,B.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,B.existsSync)(e))try{return(0,B.statSync)(e).isDirectory()?[...this.scanGlob(this.normalizeGlobPattern((0,z.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,z.join)(e,"**",`*${vi}`)))]:[e]}catch(t){return f.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){try{return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0,dot:!0}))}catch(t){let n=t?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw t}}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n,s=!1,i){if(e=ie(e),!(this.tailers.has(e)||this.startingTailers.has(e))){this.startingTailers.add(e);try{await this.startTailer(e,t,n,s,i)}finally{this.startingTailers.delete(e)}}}async startTailer(e,t,n,s,i){let o=e.endsWith(vi);if(o&&!ig()){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),l=this.state.offsets[e],u=l??0,d=!1;if(l===void 0&&t.startAtEnd)try{let m=(0,B.statSync)(e);if(s&&m.mtimeMs>=this.startedAtMs-ag&&await this.startedAfterThisWatcher(e,o,m.size)||(u=o?await Ww(e,m.size):m.size),this.stopped)return;this.state.offsets[e]=u,d=!0}catch(m){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},m instanceof Error?m:void 0),u=0}try{let m=(0,B.statSync)(e),h=Mi(m),_=this.state.fileIdentities?.[e],E=l!==void 0&&_!==void 0&&!gg(e,h,m.size,l,this.state.checkpointFingerprints?.[e]);if(E&&(u=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)),E||h!==_){(this.state.fileIdentities??={})[e]=h;let y=cc(e,u,h);y!==null?(this.state.checkpointFingerprints??={})[e]=y: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?gr(this.statePath,this.state):i&&(i.stateChanged=!0));let g=u>0&&(!!n.sessionIdPath||!!t.subagentSource||!c.cwd),p=new ac(e,u,async m=>{try{g&&(g=!1,await this.primeFromFirstLine(e,u,t,n,a,c)),await this.handleLine(m,t,n,e,a,c)}finally{c.pendingTools&&((this.state.pendingTools??={})[e]=c.pendingTools),c.cwd&&c.cwd!==this.state.cwds?.[e]&&((this.state.cwds??={})[e]=c.cwd)}},(m,h,_,E,y,w)=>{E!==void 0&&((this.state.fileIdentities??={})[e]=E),y!==void 0?(this.state.checkpointFingerprints??={})[e]=y: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],gr(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]);p.start(),this.tailers.set(e,p),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async startedAfterThisWatcher(e,t,n){let s=await Hw(e,t,n);return s!==null?s>=this.startedAtMs-ag:n<=Uw}async primeFromFirstLine(e,t,n,s,i,o){try{let a=await pg(e,e.endsWith(vi),t);if(a===null)return;await this.processor.primeSessionContext(JSON.parse(a),n,s,i,o)}catch(a){f.debug("TRANSCRIPT","Could not read the first line of a resumed transcript",{watch:n.name,file:(0,z.basename)(e)},a instanceof Error?a:void 0)}}async handleLine(e,t,n,s,i,o){try{let a=JSON.parse(e);await this.processor.processEntry(a,t,n,i??void 0,o)}catch(a){if(a instanceof gn||a instanceof mn||a instanceof Pt)throw f.warn("TRANSCRIPT","Transcript event not accepted; it is retried from its own line",{watch:t.name,file:(0,z.basename)(s),error:a.message}),a;a instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,z.basename)(s)},a):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,z.basename)(s),error:String(a)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function lc(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}function mg(r){(0,hg.existsSync)(ie(r))||(Wi(r),console.log(`Created sample config: ${ie(r)}`))}async function _g(r,e){switch(r){case"init":{let t=lc(e,"--config")??Lt;return Wi(t),console.log(`Created sample config: ${ie(t)}`),0}case"watch":{let t=lc(e,"--config")??Lt;mg(t);let n=H.loadFromFile(ne),{config:s,scoped:i,removed:o}=Dc(Bi(t),n);if(i>0&&console.log(`Scoped ${i} Codex transcript watch(es) to subagent sessions (CLAUDE_MEM_CODEX_SUBAGENT_INGESTION=true); native hooks capture top-level sessions.`),o>0&&console.log(`Skipped ${o} Codex transcript watch(es): native hooks capture top-level Codex sessions, and subagent capture is opt-in (CLAUDE_MEM_CODEX_SUBAGENT_INGESTION=true).`),s.watches.length===0)return console.log(`No active transcript watches in ${ie(t)}; nothing to watch.`),1;let a=ie(s.stateFile??Rn),c=new Ci(s,a,"spool");await c.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let l=()=>{c.stop(),process.exit(0)};return process.on("SIGINT",l),process.on("SIGTERM",l),await new Promise(()=>{})}case"validate":{let t=lc(e,"--config")??Lt;return mg(t),Bi(t),console.log(`Config OK: ${ie(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Gw=process.argv[2],zw=process.argv.slice(3);_g(Gw,zw).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
38
38
  /*! Bundled license information:
39
39
 
40
40
  @posthog/core/dist/vendor/uuidv7.mjs: