context-mode 1.0.150 → 1.0.152

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 (107) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/mcp.json +5 -1
  4. package/.codex-plugin/plugin.json +1 -1
  5. package/.openclaw-plugin/openclaw.plugin.json +16 -1
  6. package/.openclaw-plugin/package.json +1 -1
  7. package/README.md +89 -3
  8. package/build/adapters/claude-code/hooks.js +2 -2
  9. package/build/adapters/claude-code/index.js +14 -13
  10. package/build/adapters/client-map.js +3 -0
  11. package/build/adapters/detect.js +13 -1
  12. package/build/adapters/gemini-cli/hooks.d.ts +10 -0
  13. package/build/adapters/gemini-cli/hooks.js +12 -2
  14. package/build/adapters/gemini-cli/index.d.ts +21 -1
  15. package/build/adapters/gemini-cli/index.js +37 -1
  16. package/build/adapters/kimi/config.d.ts +8 -0
  17. package/build/adapters/kimi/config.js +8 -0
  18. package/build/adapters/kimi/hooks.d.ts +28 -0
  19. package/build/adapters/kimi/hooks.js +34 -0
  20. package/build/adapters/kimi/index.d.ts +66 -0
  21. package/build/adapters/kimi/index.js +537 -0
  22. package/build/adapters/kimi/paths.d.ts +1 -0
  23. package/build/adapters/kimi/paths.js +12 -0
  24. package/build/adapters/kiro/hooks.js +2 -2
  25. package/build/adapters/openclaw/plugin.d.ts +14 -13
  26. package/build/adapters/openclaw/plugin.js +140 -40
  27. package/build/adapters/opencode/plugin.js +4 -3
  28. package/build/adapters/opencode/zod3tov4.js +8 -8
  29. package/build/adapters/pi/extension.js +9 -24
  30. package/build/adapters/pi/mcp-bridge.js +37 -0
  31. package/build/adapters/qwen-code/index.js +7 -7
  32. package/build/adapters/types.d.ts +39 -2
  33. package/build/adapters/types.js +55 -2
  34. package/build/adapters/vscode-copilot/index.js +13 -1
  35. package/build/cli.js +433 -25
  36. package/build/executor.js +6 -3
  37. package/build/runtime.d.ts +81 -1
  38. package/build/runtime.js +195 -9
  39. package/build/search/ctx-search-schema.d.ts +90 -0
  40. package/build/search/ctx-search-schema.js +135 -0
  41. package/build/search/unified.d.ts +12 -0
  42. package/build/search/unified.js +17 -2
  43. package/build/server.d.ts +2 -1
  44. package/build/server.js +378 -97
  45. package/build/session/analytics.d.ts +36 -13
  46. package/build/session/analytics.js +123 -26
  47. package/build/session/db.d.ts +24 -0
  48. package/build/session/db.js +41 -0
  49. package/build/session/extract.js +30 -0
  50. package/build/session/snapshot.js +24 -0
  51. package/build/store.d.ts +12 -1
  52. package/build/store.js +72 -20
  53. package/build/types.d.ts +7 -0
  54. package/build/util/project-dir.d.ts +19 -16
  55. package/build/util/project-dir.js +80 -45
  56. package/cli.bundle.mjs +371 -320
  57. package/configs/kimi/hooks.json +54 -0
  58. package/configs/pi/AGENTS.md +3 -85
  59. package/hooks/cache-heal-utils.mjs +148 -0
  60. package/hooks/core/formatters.mjs +26 -0
  61. package/hooks/core/routing.mjs +9 -1
  62. package/hooks/core/stdin.mjs +74 -3
  63. package/hooks/core/tool-naming.mjs +1 -0
  64. package/hooks/heal-partial-install.mjs +712 -0
  65. package/hooks/kimi/platform.mjs +1 -0
  66. package/hooks/kimi/posttooluse.mjs +72 -0
  67. package/hooks/kimi/precompact.mjs +80 -0
  68. package/hooks/kimi/pretooluse.mjs +42 -0
  69. package/hooks/kimi/sessionend.mjs +61 -0
  70. package/hooks/kimi/sessionstart.mjs +113 -0
  71. package/hooks/kimi/stop.mjs +61 -0
  72. package/hooks/kimi/userpromptsubmit.mjs +90 -0
  73. package/hooks/normalize-hooks.mjs +66 -12
  74. package/hooks/routing-block.mjs +8 -2
  75. package/hooks/security.bundle.mjs +1 -1
  76. package/hooks/session-db.bundle.mjs +6 -4
  77. package/hooks/session-extract.bundle.mjs +2 -2
  78. package/hooks/session-helpers.mjs +93 -3
  79. package/hooks/session-snapshot.bundle.mjs +20 -19
  80. package/hooks/sessionstart.mjs +64 -0
  81. package/insight/server.mjs +15 -3
  82. package/openclaw.plugin.json +16 -1
  83. package/package.json +1 -1
  84. package/scripts/heal-installed-plugins.mjs +31 -10
  85. package/scripts/postinstall.mjs +10 -0
  86. package/server.bundle.mjs +206 -157
  87. package/skills/ctx-index/SKILL.md +46 -0
  88. package/skills/ctx-search/SKILL.md +35 -0
  89. package/start.mjs +84 -11
  90. package/build/cache-heal.d.ts +0 -48
  91. package/build/cache-heal.js +0 -150
  92. package/build/concurrency/runPool.d.ts +0 -36
  93. package/build/concurrency/runPool.js +0 -51
  94. package/build/openclaw/mcp-tools.d.ts +0 -54
  95. package/build/openclaw/mcp-tools.js +0 -198
  96. package/build/openclaw/workspace-router.d.ts +0 -29
  97. package/build/openclaw/workspace-router.js +0 -64
  98. package/build/openclaw-plugin.d.ts +0 -130
  99. package/build/openclaw-plugin.js +0 -626
  100. package/build/opencode-plugin.d.ts +0 -122
  101. package/build/opencode-plugin.js +0 -375
  102. package/build/pi-extension.d.ts +0 -14
  103. package/build/pi-extension.js +0 -451
  104. package/build/routing-block.d.ts +0 -8
  105. package/build/routing-block.js +0 -86
  106. package/build/tool-naming.d.ts +0 -4
  107. package/build/tool-naming.js +0 -24
package/cli.bundle.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- var CP=Object.create;var ed=Object.defineProperty;var OP=Object.getOwnPropertyDescriptor;var IP=Object.getOwnPropertyNames;var AP=Object.getPrototypeOf,NP=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Le=(t,e)=>{for(var r in e)ed(t,r,{get:e[r],enumerable:!0})},DP=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of IP(e))!NP.call(t,o)&&o!==r&&ed(t,o,{get:()=>e[o],enumerable:!(n=OP(e,o))||n.enumerable});return t};var ei=(t,e,r)=>(r=t!=null?CP(AP(t)):{},DP(e||!t||!t.__esModule?ed(r,"default",{value:t,enumerable:!0}):r,t));var ad=M((AZ,z_)=>{"use strict";var id={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},qP={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},VP={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?id.up():"");return t&&(e+=id.left),e}};z_.exports={cursor:id,scroll:qP,erase:VP,beep:"\x07"}});var q_=M((hB,md)=>{var Ka=process||{},Z_=Ka.argv||[],Ga=Ka.env||{},yR=!(Ga.NO_COLOR||Z_.includes("--no-color"))&&(!!Ga.FORCE_COLOR||Z_.includes("--color")||Ka.platform==="win32"||(Ka.stdout||{}).isTTY&&Ga.TERM!=="dumb"||!!Ga.CI),_R=(t,e,r=t)=>n=>{let o=""+n,s=o.indexOf(e,t.length);return~s?t+vR(o,e,r,s)+e:t+o+e},vR=(t,e,r,n)=>{let o="",s=0;do o+=t.substring(s,n)+r,s=n+e.length,n=t.indexOf(e,s);while(~n);return o+t.substring(s)},B_=(t=yR)=>{let e=t?_R:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};md.exports=B_();md.exports.createColors=B_});import{execFileSync as W_,execSync as ni}from"node:child_process";import{existsSync as Ja}from"node:fs";function hd(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function xR(t){return bR.test(hd(t))}function tt(t){try{let e=oi?`where ${t}`:`command -v ${t}`;return ni(e,{stdio:"pipe"}),!0}catch{return!1}}function fd(t){if(oi)try{let r=ni(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0||r.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!tt(t))return!1;try{return oi?ni(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):W_(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function G_(){if(tt("bun"))return!0;for(let t of K_())if(Ja(t))return!0;return!1}function SR(){for(let e of K_())if(Ja(e))return e;if(tt("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return oi?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function K_(){let t=process.env.HOME??process.env.USERPROFILE??"";if(oi){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function kR(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(Ja(e))return e;try{let r=ni("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Zt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return ni(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return W_(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Lo(){let e=G_()?SR():null,r=process.env.SHELL,n=r&&Ja(r)&&xR(r)?r:null,o=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(tt("tsx")?"tsx":tt("ts-node")?"ts-node":null),python:fd("python3")?"python3":fd("python")?"python":fd("py")?"py":null,shell:n??(o?kR()??(tt("sh")?"sh":tt("powershell")?"powershell":"cmd.exe"):tt("bash")?"bash":"sh"),ruby:tt("ruby")?"ruby":null,go:tt("go")?"go":null,rust:tt("rustc")?"rustc":null,php:tt("php")?"php":null,perl:tt("perl")?"perl":null,r:tt("Rscript")?"Rscript":tt("r")?"r":null,elixir:tt("elixir")?"elixir":null,csharp:tt("dotnet-script")?"dotnet-script":null}}function Bn(){return G_()}function Ya(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${Zt(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${Zt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Zt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Zt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Zt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Zt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Zt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Zt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Zt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Zt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Zt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Zt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
- `)}function Xa(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function J_(t,e,r){switch(e){case"javascript":return V_.test(hd(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return V_.test(hd(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let s=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${s}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var bR,V_,oi,Qa=S(()=>{"use strict";bR=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,V_=/^bun(\.exe)?$/i;oi=process.platform==="win32"});function Fe(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}function ec(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}var cn=S(()=>{"use strict"});function wR(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let o of n)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function ER(t){let e=ec(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function tc(t,e){let r=new Set,n=t.generateHookConfig(e);for(let o of Object.values(n))if(Array.isArray(o))for(let s of o)for(let i of wR(s)){let a=ER(i);a&&r.add(a)}return[...r]}var gd=S(()=>{"use strict";cn()});var Y_,X_=S(()=>{"use strict";Y_={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});var vd={};Le(vd,{BunSQLiteAdapter:()=>rc,NodeSQLiteAdapter:()=>nc,SQLiteBase:()=>ii,applyWALPragmas:()=>Uo,cleanOrphanedWALFiles:()=>Ho,closeDB:()=>Zo,defaultDBPath:()=>_d,deleteDBFiles:()=>oc,hasModernSqlite:()=>tv,isSQLiteCorruptionError:()=>sc,loadDatabase:()=>Qe,nodeSqliteHasFts5:()=>ev,renameCorruptDB:()=>rv,withRetry:()=>un});import{createRequire as $R}from"node:module";import{existsSync as TR,unlinkSync as Q_,renameSync as PR}from"node:fs";import{tmpdir as RR}from"node:os";import{join as CR}from"node:path";function ev(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function tv(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[o,s]=(n.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function Qe(){if(!Fo){let t=$R(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Fo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new rc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(tv()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&ev(e)?Fo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1}),i=new nc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:Fo=t("better-sqlite3")}else Fo=t("better-sqlite3")}return Fo}function Uo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Ho(t){if(!TR(t))for(let e of["-wal","-shm"])try{Q_(t+e)}catch{}}function oc(t){for(let e of["","-wal","-shm"])try{Q_(t+e)}catch{}}function Zo(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function _d(t="context-mode"){return CR(RR(),`${t}-${process.pid}.db`)}function un(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function sc(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function rv(t){let e=Date.now();for(let r of["","-wal","-shm"])try{PR(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var rc,nc,Fo,si,yd,ii,ln=S(()=>{"use strict";rc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},nc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Fo=null;si=Symbol.for("__context_mode_live_dbs_v3__"),yd=(()=>{let t=globalThis;return t[si]||(t[si]=new Set,process.on("exit",()=>{for(let e of t[si])Zo(e);t[si].clear()})),t[si]})(),ii=class{#e;#t;constructor(e){let r=Qe();this.#e=e,Ho(e);let n;try{n=new r(e,{timeout:3e4}),Uo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(sc(s)){rv(e),Ho(e);try{n=new r(e,{timeout:3e4}),Uo(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,yd.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){yd.delete(this.#t),Zo(this.#t)}withRetry(e){return un(e)}cleanup(){yd.delete(this.#t),Zo(this.#t),oc(this.#e)}}});import{createHash as ci}from"node:crypto";import{execFileSync as OR}from"node:child_process";import{accessSync as IR,constants as AR,existsSync as ac,mkdirSync as NR,realpathSync as DR,renameSync as xd}from"node:fs";import{homedir as cv}from"node:os";import{dirname as MR,isAbsolute as uv,join as dn,resolve as Bo}from"node:path";function Sd(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):dn(jR(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function jR(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?ov(n.trim()):ov(t,cv())}function ov(t,e){return t.startsWith("~")?Bo(cv(),t.replace(/^~[/\\]?/,"")):uv(t)?Bo(t):e?Bo(e,t):Bo(t)}function zR(t,e,r){return new cr(t,e,$r,void 0,[`Invalid ${$r} for context-mode ${t} directory: ${r}`,mv()].join(`
4
- `))}function dv(t){let e=process.env[$r];if(e===void 0)return{kind:"unset"};let r=e.trim();if(!r)return{kind:"ignored-empty",ignoredEnvVar:$r,ignoredReason:"empty"};if(!uv(r))throw zR(t,r,`${$r} must be an absolute path.`);return{kind:"override",root:Bo(r)}}function LR(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function pv(t,e){let r=dv(t);return r.kind!=="override"?null:{kind:t,path:dn(r.root,e),envVar:$r,source:"override"}}function FR(t,e,r){return{kind:t,path:Bo(e()),envVar:null,source:"default",...r}}function pn(t){let e=dv("session");return e.kind==="override"?{kind:"session",path:dn(e.root,lv),envVar:$r,source:"override"}:FR("session",t,LR(e))}function qo(t){let e=pv("content",nv);if(e)return e;let r=pn(t);return{kind:"content",path:dn(MR(r.path),nv),envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function ui(t){let e=pv("stats",lv);if(e)return e;let r=pn(t);return{kind:"stats",path:r.path,envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function li(t){return t.message}function cc(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function mn(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),r=bd.get(e);if(r instanceof cr)throw r;if(r===t.path)return r;try{return NR(t.path,{recursive:!0}),IR(t.path,AR.W_OK),bd.set(e,t.path),t.path}catch(n){let o=new cr(t.kind,ZR(n)??t.path,$r,n,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw bd.set(e,o),o}}function UR(t,e,r={}){return[`context-mode ${t} directory is not writable: ${e}`,HR(r),mv()].filter(Boolean).join(`
5
- `)}function HR(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function mv(){return`Set ${$r} to a writable absolute path.`}function ZR(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function di(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function sv(t){let e=t;try{e=DR.native(t)}catch{}let r=di(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function fv(t,e){return OR("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function BR(t){let e=fv(t,["rev-parse","--show-toplevel"]);return e.length>0?di(e):null}function qR(t){let e=fv(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?di(e):null}function uc(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(ai&&ai.projectDir===t&&ai.envSuffix===e)return ai.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=BR(t),o=qR(t);if(n&&o){let s=sv(n),i=sv(o);s!==i&&(r=`__${ci("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return ai={projectDir:t,envSuffix:e,suffix:r},r}function Ur(t){return ci("sha256").update(di(t)).digest("hex").slice(0,16)}function gt(t){let e=di(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return ci("sha256").update(r).digest("hex").slice(0,16)}function hv(t){let{projectDir:e,contentDir:r}=t,n=gt(e),o=dn(r,`${n}.db`);if(ac(o))return o;let s=Ur(e);if(s===n)return o;let i=dn(r,`${s}.db`);if(ac(i))try{xd(i,o);for(let a of["-wal","-shm"])try{xd(i+a,o+a)}catch{}}catch{}return o}function pi(t){return VR({...t,ext:".db"})}function VR(t){let{projectDir:e,sessionsDir:r,ext:n}=t,o=t.suffix??uc(e),s=gt(e),i=dn(r,`${s}${o}${n}`);if(ac(i))return i;let a=Ur(e);if(a===s)return i;let c=dn(r,`${a}${o}${n}`);if(ac(c))try{xd(c,i)}catch{}return i}function ic(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function gv(t){let e=t.pragma("table_xinfo(session_events)"),r=new Set(e.map(o=>o.name)),n=!1;for(let[o,s]of WR)r.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),n=!0);return n&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),n}function yv(t,e){let r=null;try{r=new e(t),gv(r)}catch{}finally{try{r?.close()}catch{}}}var $r,lv,nv,cr,bd,ai,iv,av,B,WR,ur,Tr=S(()=>{"use strict";ln();$r="CONTEXT_MODE_DIR",lv="sessions",nv="content",cr=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,r,n=$r,o,s,i={}){super(s??UR(e,r,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=r,this.overrideEnvVar=n,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},bd=new Map;iv=1e3,av=5;B={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},WR=[["project_dir","TEXT NOT NULL DEFAULT ''"],["attribution_source","TEXT NOT NULL DEFAULT 'unknown'"],["attribution_confidence","REAL NOT NULL DEFAULT 0"],["bytes_avoided","INTEGER NOT NULL DEFAULT 0"],["bytes_returned","INTEGER NOT NULL DEFAULT 0"]];ur=class extends ii{constructor(e){super(e?.dbPath??_d("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
2
+ var LR=Object.create;var yd=Object.defineProperty;var zR=Object.getOwnPropertyDescriptor;var FR=Object.getOwnPropertyNames;var HR=Object.getPrototypeOf,UR=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),we=(t,e)=>{for(var r in e)yd(t,r,{get:e[r],enumerable:!0})},BR=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of FR(e))!UR.call(t,o)&&o!==r&&yd(t,o,{get:()=>e[o],enumerable:!(n=zR(e,o))||n.enumerable});return t};var bi=(t,e,r)=>(r=t!=null?LR(HR(t)):{},BR(e||!t||!t.__esModule?yd(r,"default",{value:t,enumerable:!0}):r,t));var wd=L((yq,_b)=>{"use strict";var kd={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},QR={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},eC={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?kd.up():"");return t&&(e+=kd.left),e}};_b.exports={cursor:kd,scroll:QR,erase:eC,beep:"\x07"}});var Eb=L((Qq,Cd)=>{var hc=process||{},kb=hc.argv||[],fc=hc.env||{},EC=!(fc.NO_COLOR||kb.includes("--no-color"))&&(!!fc.FORCE_COLOR||kb.includes("--color")||hc.platform==="win32"||(hc.stdout||{}).isTTY&&fc.TERM!=="dumb"||!!fc.CI),$C=(t,e,r=t)=>n=>{let o=""+n,s=o.indexOf(e,t.length);return~s?t+TC(o,e,r,s)+e:t+o+e},TC=(t,e,r,n)=>{let o="",s=0;do o+=t.substring(s,n)+r,s=n+e.length,n=t.indexOf(e,s);while(~n);return o+t.substring(s)},wb=(t=EC)=>{let e=t?$C:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Cd.exports=wb();Cd.exports.createColors=wb});function Si(t,e){let r=process.execPath.replace(/\\/g,"/");if(Xn(e?.platform)){let o=r.split("/").pop().replace(/\.exe$/i,"");Od.has(o)||(r=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let n=t.replace(/\\/g,"/");return`"${r}" "${n}"`}function Xe(t,e){if(Xn(e?.platform))return Si(t,e);let n=Id().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${n}" "${o}"`}function gc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Xn(t){return!!t&&PC.has(t)}var Od,PC,Cr=S(()=>{"use strict";Xo();Od=new Set(["node","bun","deno"]),PC=new Set(["opencode","kilo"])});var Ob={};we(Ob,{buildCommand:()=>jd,detectRuntimes:()=>Yn,getAvailableLanguages:()=>Ei,getRuntimeSummary:()=>wi,hasBunRuntime:()=>yn,isAllowlistedShell:()=>Tb,resetHookRuntimeCache:()=>IC,resolveHookRuntime:()=>Id,resolveJavascriptRuntime:()=>Cb});import{execFileSync as Dd,execSync as Yo}from"node:child_process";import{existsSync as yc}from"node:fs";function Nd(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function Tb(t){return RC.test(Nd(t))}function CC(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function tt(t){try{let e=ki?`where ${t}`:`command -v ${t}`;return Yo(e,{stdio:"pipe"}),!0}catch{return!1}}function Ad(t){if(ki)try{let r=Yo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0||r.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!tt(t))return!1;try{return ki?Yo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Dd(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function Md(){if(tt("bun"))return!0;for(let t of Rb())if(yc(t))return!0;return!1}function Pb(){for(let e of Rb())if(yc(e))return e;if(tt("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return ki?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Rb(){let t=process.env.HOME??process.env.USERPROFILE??"";if(ki){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function OC(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(yc(e))return e;try{let r=Yo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Wt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return Yo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Dd(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Cb(t,e={}){if(t)return t;let r=e.execPath??process.execPath,n=e.commandExists??tt,o=r.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Od.has(o)?r:n("node")?"node":null}function Yn(){let e=Md()?Pb():null,r=process.env.SHELL,n=process.platform==="win32",o=r&&yc(r)&&Tb(r)&&!(n&&CC(r))?r:null;return{javascript:Cb(e),typescript:e||(tt("tsx")?"tsx":tt("ts-node")?"ts-node":null),python:Ad("python3")?"python3":Ad("python")?"python":Ad("py")?"py":null,shell:o??(n?OC()??(tt("sh")?"sh":tt("powershell")?"powershell":"cmd.exe"):tt("bash")?"bash":"sh"),ruby:tt("ruby")?"ruby":null,go:tt("go")?"go":null,rust:tt("rustc")?"rustc":null,php:tt("php")?"php":null,perl:tt("perl")?"perl":null,r:tt("Rscript")?"Rscript":tt("r")?"r":null,elixir:tt("elixir")?"elixir":null,csharp:tt("dotnet-script")?"dotnet-script":null}}function yn(){return Md()}function IC(){zt=null}function AC(t){let e=t.trim(),r=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!r)return!1;let n=Number(r[1]);return Number.isFinite(n)&&n>=1}function Id(){if(zt)return zt;let t={path:process.execPath,isBun:!1};try{if(!Md())return zt=t,zt;let e=Pb(),r;try{if(process.platform==="win32"){let n=Yo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});r=String(n)}else{let n=Dd(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});r=String(n)}}catch{return zt=t,zt}return AC(r)?(zt={path:e,isBun:!0},zt):(zt=t,zt)}catch{return zt=t,zt}}function wi(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Wt(t.javascript)})${r?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${Wt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Wt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Wt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Wt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Wt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Wt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Wt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Wt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Wt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Wt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Wt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
+ `)}function Ei(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function jd(t,e,r){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return $b.test(Nd(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return $b.test(Nd(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",r];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var RC,$b,ki,zt,Xo=S(()=>{"use strict";Cr();RC=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,$b=/^bun(\.exe)?$/i;ki=process.platform==="win32";zt=null});function NC(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let o of n)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function DC(t){let e=gc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function _c(t,e){let r=new Set,n=t.generateHookConfig(e);for(let o of Object.values(n))if(Array.isArray(o))for(let s of o)for(let i of NC(s)){let a=DC(i);a&&r.add(a)}return[...r]}var Ld=S(()=>{"use strict";Cr()});var Ib,Ab=S(()=>{"use strict";Ib={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});var Hd={};we(Hd,{BunSQLiteAdapter:()=>bc,NodeSQLiteAdapter:()=>xc,SQLiteBase:()=>Ti,applyWALPragmas:()=>es,cleanOrphanedWALFiles:()=>ts,closeDB:()=>rs,defaultDBPath:()=>Fd,deleteDBFiles:()=>vc,hasModernSqlite:()=>Mb,isSQLiteCorruptionError:()=>Sc,loadDatabase:()=>rt,nodeSqliteHasFts5:()=>Db,renameCorruptDB:()=>jb,withRetry:()=>_n});import{createRequire as MC}from"node:module";import{existsSync as jC,unlinkSync as Nb,renameSync as LC}from"node:fs";import{tmpdir as zC}from"node:os";import{join as FC}from"node:path";function Db(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function Mb(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[o,s]=(n.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function rt(){if(!Qo){let t=MC(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Qo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new bc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(Mb()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&Db(e)?Qo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1}),i=new xc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:Qo=t("better-sqlite3")}else Qo=t("better-sqlite3")}return Qo}function es(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function ts(t){if(!jC(t))for(let e of["-wal","-shm"])try{Nb(t+e)}catch{}}function vc(t){for(let e of["","-wal","-shm"])try{Nb(t+e)}catch{}}function rs(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Fd(t="context-mode"){return FC(zC(),`${t}-${process.pid}.db`)}function _n(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function Sc(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function jb(t){let e=Date.now();for(let r of["","-wal","-shm"])try{LC(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var bc,xc,Qo,$i,zd,Ti,bn=S(()=>{"use strict";bc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},xc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Qo=null;$i=Symbol.for("__context_mode_live_dbs_v3__"),zd=(()=>{let t=globalThis;return t[$i]||(t[$i]=new Set,process.on("exit",()=>{for(let e of t[$i])rs(e);t[$i].clear()})),t[$i]})(),Ti=class{#e;#t;constructor(e){let r=rt();this.#e=e,ts(e);let n;try{n=new r(e,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Sc(s)){jb(e),ts(e);try{n=new r(e,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,zd.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){zd.delete(this.#t),rs(this.#t)}withRetry(e){return _n(e)}cleanup(){zd.delete(this.#t),rs(this.#t),vc(this.#e)}}});var Xb={};we(Xb,{SessionDB:()=>Gt,StorageDirectoryError:()=>Kt,_resetWorktreeSuffixCacheForTests:()=>nO,applyMissingSessionEventsColumns:()=>Zd,clearStorageDirectoryCheckCacheForTests:()=>XC,describeStorageDirectorySource:()=>Ri,ensureSessionEventsSchema:()=>qd,ensureWritableStorageDir:()=>Ir,formatStorageDirectoryError:()=>is,getWorktreeSuffix:()=>Ci,hashProjectDirCanonical:()=>nt,hashProjectDirLegacy:()=>Ar,normalizeWorktreePath:()=>as,resolveContentStorageDir:()=>vn,resolveContentStorePath:()=>Bd,resolveDefaultSessionDir:()=>$c,resolveSessionDbPath:()=>cs,resolveSessionPath:()=>Jb,resolveSessionStorageDir:()=>Jr,resolveStatsStorageDir:()=>ss});import{createHash as Pi}from"node:crypto";import{execFileSync as HC}from"node:child_process";import{accessSync as UC,constants as BC,existsSync as Ec,mkdirSync as ZC,realpathSync as qC,renameSync as Ud}from"node:fs";import{homedir as Bb}from"node:os";import{dirname as VC,isAbsolute as Zb,join as xn,resolve as os}from"node:path";function $c(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):xn(WC(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function WC(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?zb(n.trim()):zb(t,Bb())}function zb(t,e){return t.startsWith("~")?os(Bb(),t.replace(/^~[/\\]?/,"")):Zb(t)?os(t):e?os(e,t):os(t)}function KC(t,e,r){return new Kt(t,e,Or,void 0,[`Invalid ${Or} for context-mode ${t} directory: ${r}`,Kb()].join(`
4
+ `))}function Vb(t){let e=process.env[Or];if(e===void 0)return{kind:"unset"};let r=e.trim();if(!r)return{kind:"ignored-empty",ignoredEnvVar:Or,ignoredReason:"empty"};if(!Zb(r))throw KC(t,r,`${Or} must be an absolute path.`);return{kind:"override",root:os(r)}}function GC(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function Wb(t,e){let r=Vb(t);return r.kind!=="override"?null:{kind:t,path:xn(r.root,e),envVar:Or,source:"override"}}function JC(t,e,r){return{kind:t,path:os(e()),envVar:null,source:"default",...r}}function Jr(t){let e=Vb("session");return e.kind==="override"?{kind:"session",path:xn(e.root,qb),envVar:Or,source:"override"}:JC("session",t,GC(e))}function vn(t){let e=Wb("content",Lb);if(e)return e;let r=Jr(t);return{kind:"content",path:xn(VC(r.path),Lb),envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function ss(t){let e=Wb("stats",qb);if(e)return e;let r=Jr(t);return{kind:"stats",path:r.path,envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function is(t){return t.message}function Ri(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function XC(){wc.clear()}function Ir(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),r=wc.get(e);if(r instanceof Kt)throw r;if(r===t.path)return r;try{return ZC(t.path,{recursive:!0}),UC(t.path,BC.W_OK),wc.set(e,t.path),t.path}catch(n){let o=new Kt(t.kind,eO(n)??t.path,Or,n,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw wc.set(e,o),o}}function YC(t,e,r={}){return[`context-mode ${t} directory is not writable: ${e}`,QC(r),Kb()].filter(Boolean).join(`
5
+ `)}function QC(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function Kb(){return`Set ${Or} to a writable absolute path.`}function eO(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function as(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function Fb(t){let e=t;try{e=qC.native(t)}catch{}let r=as(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function Gb(t,e){return HC("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function tO(t){let e=Gb(t,["rev-parse","--show-toplevel"]);return e.length>0?as(e):null}function rO(t){let e=Gb(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?as(e):null}function Ci(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(ns&&ns.projectDir===t&&ns.envSuffix===e)return ns.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=tO(t),o=rO(t);if(n&&o){let s=Fb(n),i=Fb(o);s!==i&&(r=`__${Pi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return ns={projectDir:t,envSuffix:e,suffix:r},r}function nO(){ns=void 0}function Ar(t){return Pi("sha256").update(as(t)).digest("hex").slice(0,16)}function nt(t){let e=as(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Pi("sha256").update(r).digest("hex").slice(0,16)}function Bd(t){let{projectDir:e,contentDir:r}=t,n=nt(e),o=xn(r,`${n}.db`);if(Ec(o))return o;let s=Ar(e);if(s===n)return o;let i=xn(r,`${s}.db`);if(Ec(i))try{Ud(i,o);for(let a of["-wal","-shm"])try{Ud(i+a,o+a)}catch{}}catch{}return o}function cs(t){return Jb({...t,ext:".db"})}function Jb(t){let{projectDir:e,sessionsDir:r,ext:n}=t,o=t.suffix??Ci(e),s=nt(e),i=xn(r,`${s}${o}${n}`);if(Ec(i))return i;let a=Ar(e);if(a===s)return i;let c=xn(r,`${a}${o}${n}`);if(Ec(c))try{Ud(c,i)}catch{}return i}function kc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function Zd(t){let e=t.pragma("table_xinfo(session_events)"),r=new Set(e.map(o=>o.name)),n=!1;for(let[o,s]of oO)r.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),n=!0);return n&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),n}function qd(t,e){let r=null;try{r=new e(t),Zd(r)}catch{}finally{try{r?.close()}catch{}}}var Or,qb,Lb,Kt,wc,ns,Hb,Ub,Z,oO,Gt,Jt=S(()=>{"use strict";bn();Or="CONTEXT_MODE_DIR",qb="sessions",Lb="content",Kt=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,r,n=Or,o,s,i={}){super(s??YC(e,r,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=r,this.overrideEnvVar=n,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},wc=new Map;Hb=1e3,Ub=5;Z={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},oO=[["project_dir","TEXT NOT NULL DEFAULT ''"],["attribution_source","TEXT NOT NULL DEFAULT 'unknown'"],["attribution_confidence","REAL NOT NULL DEFAULT 0"],["bytes_avoided","INTEGER NOT NULL DEFAULT 0"],["bytes_returned","INTEGER NOT NULL DEFAULT 0"]];Gt=class extends Ti{constructor(e){super(e?.dbPath??Fd("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
6
6
  CREATE TABLE IF NOT EXISTS session_events (
7
7
  id INTEGER PRIMARY KEY AUTOINCREMENT,
8
8
  session_id TEXT NOT NULL,
@@ -52,50 +52,50 @@ var CP=Object.create;var ed=Object.defineProperty;var OP=Object.getOwnPropertyDe
52
52
  );
53
53
 
54
54
  CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
55
- `);try{gv(this.db)}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(B.insertEvent,`INSERT INTO session_events (
55
+ `);try{Zd(this.db)}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(Z.insertEvent,`INSERT INTO session_events (
56
56
  session_id, type, category, priority, data,
57
57
  project_dir, attribution_source, attribution_confidence,
58
58
  bytes_avoided, bytes_returned,
59
59
  source_hook, data_hash
60
60
  )
61
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(B.getEvents,`SELECT id, session_id, type, category, priority, data,
61
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(Z.getEvents,`SELECT id, session_id, type, category, priority, data,
62
62
  project_dir, attribution_source, attribution_confidence,
63
63
  bytes_avoided, bytes_returned,
64
64
  source_hook, created_at, data_hash
65
- FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByType,`SELECT id, session_id, type, category, priority, data,
65
+ FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(Z.getEventsByType,`SELECT id, session_id, type, category, priority, data,
66
66
  project_dir, attribution_source, attribution_confidence,
67
67
  bytes_avoided, bytes_returned,
68
68
  source_hook, created_at, data_hash
69
- FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
69
+ FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(Z.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
70
70
  project_dir, attribution_source, attribution_confidence,
71
71
  bytes_avoided, bytes_returned,
72
72
  source_hook, created_at, data_hash
73
- FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
73
+ FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(Z.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
74
74
  project_dir, attribution_source, attribution_confidence,
75
75
  bytes_avoided, bytes_returned,
76
76
  source_hook, created_at, data_hash
77
- FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(B.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(B.getLatestAttributedProject,`SELECT project_dir
77
+ FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(Z.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(Z.getLatestAttributedProject,`SELECT project_dir
78
78
  FROM session_events
79
79
  WHERE session_id = ? AND project_dir != ''
80
80
  ORDER BY id DESC
81
- LIMIT 1`),e(B.checkDuplicate,`SELECT 1 FROM (
81
+ LIMIT 1`),e(Z.checkDuplicate,`SELECT 1 FROM (
82
82
  SELECT type, data_hash FROM session_events
83
83
  WHERE session_id = ? ORDER BY id DESC LIMIT ?
84
84
  ) AS recent
85
85
  WHERE recent.type = ? AND recent.data_hash = ?
86
- LIMIT 1`),e(B.evictLowestPriority,`DELETE FROM session_events WHERE id = (
86
+ LIMIT 1`),e(Z.evictLowestPriority,`DELETE FROM session_events WHERE id = (
87
87
  SELECT id FROM session_events WHERE session_id = ?
88
88
  ORDER BY priority ASC, id ASC LIMIT 1
89
- )`),e(B.updateMetaLastEvent,`UPDATE session_meta
89
+ )`),e(Z.updateMetaLastEvent,`UPDATE session_meta
90
90
  SET last_event_at = datetime('now'), event_count = event_count + 1
91
- WHERE session_id = ?`),e(B.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(B.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
92
- FROM session_meta WHERE session_id = ?`),e(B.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(B.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
91
+ WHERE session_id = ?`),e(Z.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(Z.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
92
+ FROM session_meta WHERE session_id = ?`),e(Z.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(Z.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
93
93
  VALUES (?, ?, ?)
94
94
  ON CONFLICT(session_id) DO UPDATE SET
95
95
  snapshot = excluded.snapshot,
96
96
  event_count = excluded.event_count,
97
97
  created_at = datetime('now'),
98
- consumed = 0`),e(B.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(B.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(B.claimLatestUnconsumedResume,`UPDATE session_resume
98
+ consumed = 0`),e(Z.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(Z.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(Z.claimLatestUnconsumedResume,`UPDATE session_resume
99
99
  SET consumed = 1
100
100
  WHERE id = (
101
101
  SELECT id FROM session_resume
@@ -104,169 +104,59 @@ var CP=Object.create;var ed=Object.defineProperty;var OP=Object.getOwnPropertyDe
104
104
  ORDER BY created_at DESC, id DESC
105
105
  LIMIT 1
106
106
  )
107
- RETURNING session_id, snapshot`),e(B.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(B.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(B.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(B.searchEvents,`SELECT id, session_id, category, type, data, created_at
107
+ RETURNING session_id, snapshot`),e(Z.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(Z.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(Z.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(Z.searchEvents,`SELECT id, session_id, category, type, data, created_at
108
108
  FROM session_events
109
109
  WHERE (project_dir = ? OR project_dir = '')
110
110
  AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
111
111
  AND (? IS NULL OR category = ?)
112
112
  ORDER BY id ASC
113
- LIMIT ?`),e(B.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(B.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
113
+ LIMIT ?`),e(Z.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(Z.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
114
114
  VALUES (?, ?, 1, ?)
115
115
  ON CONFLICT(session_id, tool) DO UPDATE SET
116
116
  calls = calls + 1,
117
117
  bytes_returned = bytes_returned + excluded.bytes_returned,
118
- updated_at = datetime('now')`),e(B.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
118
+ updated_at = datetime('now')`),e(Z.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
119
119
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
120
- FROM tool_calls WHERE session_id = ?`),e(B.getToolCallByTool,`SELECT tool, calls, bytes_returned
121
- FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(B.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
120
+ FROM tool_calls WHERE session_id = ?`),e(Z.getToolCallByTool,`SELECT tool, calls, bytes_returned
121
+ FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(Z.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
122
122
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
123
- FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",o,s){let i=ci("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??r.attribution_source??"unknown"),u=Number(o?.confidence??r.attribution_confidence??0),d=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,l=ic(s?.bytesAvoided),m=ic(s?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(B.checkDuplicate).get(e,av,r.type,i))return;this.stmt(B.getEventCount).get(e).cnt>=iv&&this.stmt(B.evictLowestPriority).run(e),this.stmt(B.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,m,n,i),this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,r,n="PostToolUse",o,s){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,o?.[0],s?.[0]);return}let i=r.map((c,u)=>{let d=ci("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=o?.[u],m=String(l?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),f=String(l?.source??c.attribution_source??"unknown"),p=Number(l?.confidence??c.attribution_confidence??0),h=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=s?.[u],y=ic(g?.bytesAvoided),v=ic(g?.bytesReturned);return{event:c,dataHash:d,projectDir:m,attributionSource:f,attributionConfidence:h,bytesAvoided:y,bytesReturned:v}}),a=this.db.transaction(()=>{let c=this.stmt(B.getEventCount).get(e).cnt;for(let u of i)this.stmt(B.checkDuplicate).get(e,av,u.event.type,u.dataHash)||(c>=iv?this.stmt(B.evictLowestPriority).run(e):c++,this.stmt(B.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,o=r?.type,s=r?.minPriority;return o&&s!==void 0?this.stmt(B.getEventsByTypeAndPriority).all(e,o,s,n):o?this.stmt(B.getEventsByType).all(e,o,n):s!==void 0?this.stmt(B.getEventsByPriority).all(e,s,n):this.stmt(B.getEvents).all(e,n)}getEventCount(e){return this.stmt(B.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(B.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(B.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,r,n,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(B.searchEvents).all(n,s,s,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(B.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(B.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(B.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(B.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(B.getResume).get(e)??null}markResumeConsumed(e){this.stmt(B.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(B.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(B.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(B.getToolCallTotals).get(e),n=this.stmt(B.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(B.deleteEvents).run(e),this.stmt(B.deleteResume).run(e),this.stmt(B.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(B.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}}});import{join as Vo,resolve as _v}from"node:path";import{accessSync as GR,copyFileSync as KR,constants as JR,mkdirSync as YR}from"node:fs";import{homedir as kd}from"node:os";function lr(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?_v(kd(),e.replace(/^~[/\\]?/,"")):_v(e)}var Se,yt=S(()=>{"use strict";Tr();Se=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=lr(),r=e?Vo(e,"context-mode","sessions"):Vo(kd(),...this.sessionDirSegments,"context-mode","sessions");return YR(r,{recursive:!0}),r}getConfigDir(e){return Vo(kd(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let r=lr(),n=r?Vo(r,"context-mode","memory"):Vo(this.getConfigDir(),"memory");return e?Vo(n,gt(e)):n}backupSettings(){let e=this.getSettingsPath();try{GR(e,JR.R_OK);let r=e+".bak";return KR(e,r),r}catch{return null}}}});var Wo,wd=S(()=>{"use strict";yt();Wo=class extends Se{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as Ed}from"node:fs";import{join as $d}from"node:path";async function XR(){if(Go)return Go;if(Ko)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return Go=n,Go}catch(n){e=n}return Ko=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return Ko=t instanceof Error?t.message:String(t),null}}function QR(t){let e=[];return Ed($d(t,"start.mjs"))||e.push("start.mjs"),!Ed($d(t,"server.bundle.mjs"))&&!Ed($d(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function vv(t){if(Go){let e=Go.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(Ko){let e=QR(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${Ko}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${Ko}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var Go,Ko,bv=S(()=>{"use strict";Go=null,Ko=null;XR()});function mi(t,e){let r=qn[e],n=Pd(e);return t.hooks?.some(o=>o.command?.includes(r)||o.command?.includes(n))??!1}function Pd(t,e){if(e){let r=qn[t];return Fe(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Rd(t){let e=ec(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function kv(t){let e=Object.values(qn);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var dr,eC,Td,xv,tC,qB,qn,Sv,VB,wv=S(()=>{"use strict";cn();dr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},eC="mcp__",Td=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",eC],xv=Td.join("|"),tC=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],qB=tC.join("|"),qn={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},Sv=[dr.PRE_TOOL_USE,dr.SESSION_START],VB=[dr.POST_TOOL_USE,dr.PRE_COMPACT,dr.USER_PROMPT_SUBMIT]});var Od={};Le(Od,{ClaudeCodeAdapter:()=>Cd});import{readFileSync as lc,writeFileSync as Ev,existsSync as $v,readdirSync as rC,chmodSync as nC,accessSync as oC,mkdirSync as sC,constants as iC}from"node:fs";import{resolve as dc,join as fn}from"node:path";import{homedir as Tv}from"node:os";var Cd,Id=S(()=>{"use strict";wd();yt();hn();bv();cn();wv();Cd=class extends Wo{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return qe()}getSessionDir(){let e=lr(),r=e?fn(e,"context-mode","sessions"):fn(this.getConfigDir(),"context-mode","sessions");return sC(r,{recursive:!0}),r}getSettingsPath(){return fn(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=Fe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...Td].map(o=>({matcher:o,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=lc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Ev(this.getSettingsPath(),JSON.stringify(e,null,2)+`
124
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,dr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,dr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(qn).map(([o,s])=>{let i=fn(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>$v(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>vv(e)};return[...r,n]}readPluginHooks(e){let r=[fn(e,"hooks","hooks.json"),fn(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let o=lc(n,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,r,n){let o=e?.[n];if(o&&o.length>0&&o.some(i=>mi(i,n)))return!0;let s=r?.[n];return!!(s&&s.length>0&&s.some(i=>mi(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(o=>o.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=fn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(lc(r,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),qe(),dc(Tv(),".claude"),dc(Tv(),".config","claude")]));for(let r of e){let n=dc(r,"plugins","cache","context-mode","context-mode");try{let s=rC(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let d=0;d<3;d++)if((c[d]??0)!==(u[d]??0))return(c[d]??0)-(u[d]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(l=>{let m=l;if(!kv(m))return!0;let f=m.hooks??[];return f.every(h=>!h.command||!Rd(h.command))?!0:f.every(h=>{let g=h.command?Rd(h.command):null;return g?$v(g):!0})}),d=c.length-u.length;d>0&&(n[a]=u,o.push(`Removed ${d} stale ${a} hook(s)`))}let s=this.readPluginHooks(e);if(s&&Sv.every(c=>this.checkHookType(void 0,s,c))){let c=Object.values(qn),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let m=0;for(let p of l){let h=p,g=h.hooks??[],y=g.length;h.hooks=g.filter(v=>!u(v.command)),m+=y-h.hooks.length}let f=l.filter(p=>{let h=p.hooks;return Array.isArray(h)&&h.length>0});(m>0||f.length!==l.length)&&(n[d]=f,m>0&&o.push(`Removed ${m} duplicate ${d} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let i=[dr.PRE_TOOL_USE,dr.SESSION_START];for(let a of i){let c=Pd(a,e);if(a===dr.PRE_TOOL_USE){let u={matcher:xv,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(m=>mi(m,a));l>=0?(d[l]=u,o.push(`Updated existing ${a} hook entry`)):(d.push(u),o.push(`Added ${a} hook entry`)),n.PreToolUse=d}else n.PreToolUse=[u],o.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},d=n[a];if(d&&Array.isArray(d)){let l=d.findIndex(m=>mi(m,a));l>=0?(d[l]=u,o.push(`Updated existing ${a} hook entry`)):(d.push(u),o.push(`Added ${a} hook entry`)),n[a]=d}else n[a]=[u],o.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(qn)){let o=dc(e,"hooks",n);try{oC(o,iC.R_OK),nC(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=fn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(lc(n,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();Ev(n,JSON.stringify(o,null,2)+`
125
- `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function Vn(t,e){let r=Ad[t];return e&&r?Fe(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var Te,Pv,Ad,oq,sq,Rv=S(()=>{"use strict";cn();Te={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Pv="mcp__(?!.*context-mode)",Ad={[Te.BEFORE_AGENT]:"beforeagent.mjs",[Te.BEFORE_TOOL]:"beforetool.mjs",[Te.AFTER_TOOL]:"aftertool.mjs",[Te.PRE_COMPRESS]:"precompress.mjs",[Te.SESSION_START]:"sessionstart.mjs"},oq=[Te.BEFORE_TOOL,Te.SESSION_START],sq=[Te.AFTER_TOOL,Te.PRE_COMPRESS]});var Ov={};Le(Ov,{GeminiCLIAdapter:()=>Dd});import{readFileSync as Nd,writeFileSync as Cv,mkdirSync as aC,accessSync as cC,chmodSync as uC,constants as lC}from"node:fs";import{resolve as fi,join as dC}from"node:path";import{homedir as pc}from"node:os";var Dd,Iv=S(()=>{"use strict";yt();Rv();Dd=class extends Se{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return fi(pc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[Te.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:Vn(Te.BEFORE_AGENT,e)}]}],[Te.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${Pv}`,hooks:[{type:"command",command:Vn(Te.BEFORE_TOOL,e)}]}],[Te.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:Vn(Te.AFTER_TOOL,e)}]}],[Te.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:Vn(Te.PRE_COMPRESS,e)}]}],[Te.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:Vn(Te.SESSION_START,e)}]}]}}readSettings(){try{let e=Nd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=fi(pc(),".gemini");aC(r,{recursive:!0}),Cv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
126
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[Te.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[Te.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(r).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=fi(pc(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Nd(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[],s=[{name:Te.BEFORE_AGENT},{name:Te.BEFORE_TOOL},{name:Te.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:Vn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(f=>f.command?.includes("context-mode")));d>=0?(u[d]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[],n=dC(e,"hooks","gemini-cli");for(let o of Object.values(Ad)){let s=fi(n,o);try{cC(s,lC.R_OK),uC(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=fi(pc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Nd(n,"utf-8"));o.version=r,o.installPath=e,o.lastUpdated=new Date().toISOString(),Cv(n,JSON.stringify(o,null,2)+`
127
- `,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var Wn,mq,fq,Av=S(()=>{"use strict";Wn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},mq=[Wn.BEFORE,Wn.AFTER],fq=[Wn.COMPACTING]});var Dv={};Le(Dv,{OpenCodeAdapter:()=>Md});import{readFileSync as Nv,writeFileSync as mC,mkdirSync as fC,copyFileSync as hC,accessSync as gC,constants as yC}from"node:fs";import{resolve as Bt,join as Hr}from"node:path";import{homedir as gn}from"node:os";function pC(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Md,Mv=S(()=>{"use strict";yt();Av();Md=class extends Se{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??Bt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Bt("kilo.json"),Bt("kilo.jsonc"),Bt(".kilo","kilo.json"),Bt(".kilo","kilo.jsonc"),Bt(".kilocode","kilo.json"),Bt(".kilocode","kilo.jsonc"),Hr(gn(),".config","kilo","kilo.json"),Hr(gn(),".config","kilo","kilo.jsonc")]:[Bt("opencode.json"),Bt("opencode.jsonc"),Bt(".opencode","opencode.json"),Bt(".opencode","opencode.jsonc"),Hr(gn(),".config","opencode","opencode.json"),Hr(gn(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=lr(),r=e?Hr(e,"context-mode","sessions"):Hr(this.getConfigDir(),"context-mode","sessions");return fC(r,{recursive:!0}),r}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Hr(gn(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Hr(gn(),".config"),Hr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[Wn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Wn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Wn.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(s=>s.includes(gn()))),n=null,o;for(let s of e)try{let i=Nv(s,"utf-8"),a=s.endsWith(".jsonc")?pC(i):i,c=JSON.parse(a);n||(n=c,o=s);let u=r.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return n?(this.settingsPath=o,n):null}writeSettings(e){mC(this.getSettingsPath(),JSON.stringify(e,null,2)+`
128
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(n)&&r.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Bt(gn(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(Nv(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],o=r.plugin??[];o.some(i=>i.includes("context-mode"))?n.push("context-mode already in plugin array"):(o.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=o;let s=r.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],n.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete r.mcp}return this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{gC(this.settingsPath,yC.R_OK);let r=this.settingsPath+".bak";return hC(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}hasLegacyContextModeMcp(e){let r=e.mcp;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var Gn,xq,Sq,jv=S(()=>{"use strict";Gn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},xq=[Gn.TOOL_CALL_BEFORE,Gn.TOOL_CALL_AFTER],Sq=[Gn.COMMAND_NEW]});var zv={};Le(zv,{OpenClawAdapter:()=>Fd});import{readFileSync as jd,writeFileSync as _C,copyFileSync as vC,accessSync as bC,constants as xC}from"node:fs";import{resolve as Zr,join as zd}from"node:path";import{homedir as Ld}from"node:os";var Fd,Lv=S(()=>{"use strict";yt();jv();Fd=class extends Se{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Zr("openclaw.json")}getConfigDir(e){return Zr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return zd(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[Gn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Gn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Gn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Zr("openclaw.json"),Zr(".openclaw","openclaw.json"),zd(Ld(),".openclaw","openclaw.json")];for(let r of e)try{let n=jd(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Zr("openclaw.json");_C(r,JSON.stringify(e,null,2)+`
129
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Zr(Ld(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(jd(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Zr("node_modules","context-mode","package.json"),r=JSON.parse(jd(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let o=r.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Zr("openclaw.json"),Zr(".openclaw","openclaw.json"),zd(Ld(),".openclaw","openclaw.json")];for(let r of e)try{bC(r,xC.R_OK);let n=r+".bak";return vC(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as Fv}from"node:os";import{resolve as Ud}from"node:path";function Uv(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Ud(Fv(),t.replace(/^~[/\\]?/,"")):Ud(t):Ud(Fv(),".codex")}var Hv=S(()=>{"use strict"});var Wv={};Le(Wv,{CodexAdapter:()=>Bd,probeCodexCliVersion:()=>Bv});import{execFileSync as SC}from"node:child_process";import{readFileSync as Jo,writeFileSync as Zv,accessSync as kC,copyFileSync as wC,constants as EC,mkdirSync as Hd}from"node:fs";import{resolve as $C,dirname as Zd,join as Kn}from"node:path";import{fileURLToPath as TC}from"node:url";function Bv(t=SC){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),r=String(e).trim();return r.length>0?r:"available (version output empty)"}catch{return null}}function qv(t,e){let r=t.split(/\r?\n/),n=!1,o=[];for(let s of r){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&o.push(s)}return n?o.join(`
130
- `):null}function Vv(t){let e=qv(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function CC(t){let e=qv(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function OC(t){if(Vv(t))return{text:t,changed:!1};let e=t.includes(`\r
123
+ FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",o,s){let i=Pi("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??r.attribution_source??"unknown"),u=Number(o?.confidence??r.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=kc(s?.bytesAvoided),m=kc(s?.bytesReturned),h=this.db.transaction(()=>{if(this.stmt(Z.checkDuplicate).get(e,Ub,r.type,i))return;this.stmt(Z.getEventCount).get(e).cnt>=Hb&&this.stmt(Z.evictLowestPriority).run(e),this.stmt(Z.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,l,d,m,n,i),this.stmt(Z.updateMetaLastEvent).run(e)});this.withRetry(()=>h())}bulkInsertEvents(e,r,n="PostToolUse",o,s){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,o?.[0],s?.[0]);return}let i=r.map((c,u)=>{let l=Pi("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],m=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),h=String(d?.source??c.attribution_source??"unknown"),p=Number(d?.confidence??c.attribution_confidence??0),f=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=s?.[u],y=kc(g?.bytesAvoided),_=kc(g?.bytesReturned);return{event:c,dataHash:l,projectDir:m,attributionSource:h,attributionConfidence:f,bytesAvoided:y,bytesReturned:_}}),a=this.db.transaction(()=>{let c=this.stmt(Z.getEventCount).get(e).cnt;for(let u of i)this.stmt(Z.checkDuplicate).get(e,Ub,u.event.type,u.dataHash)||(c>=Hb?this.stmt(Z.evictLowestPriority).run(e):c++,this.stmt(Z.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(Z.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,o=r?.type,s=r?.minPriority;return o&&s!==void 0?this.stmt(Z.getEventsByTypeAndPriority).all(e,o,s,n):o?this.stmt(Z.getEventsByType).all(e,o,n):s!==void 0?this.stmt(Z.getEventsByPriority).all(e,s,n):this.stmt(Z.getEvents).all(e,n)}getEventCount(e){return this.stmt(Z.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(Z.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(Z.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,r,n,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(Z.searchEvents).all(n,s,s,i,i,r)}catch{return[]}}getSessionIdsForProject(e){try{return this.db.prepare(`SELECT DISTINCT session_id
124
+ FROM session_events
125
+ WHERE project_dir = ?`).all(e).map(n=>n.session_id)}catch{return[]}}ensureSession(e,r){this.stmt(Z.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(Z.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(Z.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(Z.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(Z.getResume).get(e)??null}markResumeConsumed(e){this.stmt(Z.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(Z.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(Z.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(Z.getToolCallTotals).get(e),n=this.stmt(Z.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(Z.deleteEvents).run(e),this.stmt(Z.deleteResume).run(e),this.stmt(Z.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(Z.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as us,resolve as Yb}from"node:path";import{accessSync as sO,copyFileSync as iO,constants as aO,mkdirSync as cO}from"node:fs";import{homedir as Vd}from"node:os";function Pt(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?Yb(Vd(),e.replace(/^~[/\\]?/,"")):Yb(e)}var be,pt=S(()=>{"use strict";Jt();be=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=Pt(),r=e?us(e,"context-mode","sessions"):us(Vd(),...this.sessionDirSegments,"context-mode","sessions");return cO(r,{recursive:!0}),r}getConfigDir(e){return us(Vd(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let r=Pt(),n=r?us(r,"context-mode","memory"):us(this.getConfigDir(),"memory");return e?us(n,nt(e)):n}backupSettings(){let e=this.getSettingsPath();try{sO(e,aO.R_OK);let r=e+".bak";return iO(e,r),r}catch{return null}}}});var ls,Wd=S(()=>{"use strict";pt();ls=class extends be{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as Kd}from"node:fs";import{join as Gd}from"node:path";async function uO(){if(ds)return ds;if(ps)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return ds=n,ds}catch(n){e=n}return ps=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return ps=t instanceof Error?t.message:String(t),null}}function lO(t){let e=[];return Kd(Gd(t,"start.mjs"))||e.push("start.mjs"),!Kd(Gd(t,"server.bundle.mjs"))&&!Kd(Gd(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Qb(t){if(ds){let e=ds.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(ps){let e=lO(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${ps}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${ps}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ds,ps,ex=S(()=>{"use strict";ds=null,ps=null;uO()});function Oi(t,e){let r=Qn[e],n=Xd(e);return t.hooks?.some(o=>o.command?.includes(r)||o.command?.includes(n))??!1}function Xd(t,e){if(e){let r=Qn[t];return Xe(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Yd(t){let e=gc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function nx(t){let e=Object.values(Qn);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var fr,dO,Jd,tx,pO,R4,Qn,rx,C4,ox=S(()=>{"use strict";Cr();fr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},dO="mcp__",Jd=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",dO],tx=Jd.join("|"),pO=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],R4=pO.join("|"),Qn={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},rx=[fr.PRE_TOOL_USE,fr.SESSION_START],C4=[fr.POST_TOOL_USE,fr.PRE_COMPACT,fr.USER_PROMPT_SUBMIT]});var ep={};we(ep,{ClaudeCodeAdapter:()=>Qd});import{readFileSync as Tc,writeFileSync as sx,existsSync as ix,readdirSync as mO,chmodSync as fO,accessSync as hO,mkdirSync as gO,constants as yO}from"node:fs";import{resolve as Pc,join as Sn}from"node:path";import{homedir as ax}from"node:os";var Qd,tp=S(()=>{"use strict";Wd();pt();kn();ex();Cr();ox();Qd=class extends ls{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return qe()}getSessionDir(){let e=Pt(),r=e?Sn(e,"context-mode","sessions"):Sn(this.getConfigDir(),"context-mode","sessions");return gO(r,{recursive:!0}),r}getSettingsPath(){return Sn(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=Xe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...Jd].map(o=>({matcher:o,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=Tc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){sx(this.getSettingsPath(),JSON.stringify(e,null,2)+`
126
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,fr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,fr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(Qn).map(([o,s])=>{let i=Sn(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>ix(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>Qb(e)};return[...r,n]}readPluginHooks(e){let r=[Sn(e,"hooks","hooks.json"),Sn(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let o=Tc(n,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,r,n){let o=e?.[n];if(o&&o.length>0&&o.some(i=>Oi(i,n)))return!0;let s=r?.[n];return!!(s&&s.length>0&&s.some(i=>Oi(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(o=>o.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=Sn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Tc(r,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),qe(),Pc(ax(),".claude"),Pc(ax(),".config","claude")]));for(let r of e){let n=Pc(r,"plugins","cache","context-mode","context-mode");try{let s=mO(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(d=>{let m=d;if(!nx(m))return!0;let h=m.hooks??[];return h.every(f=>!f.command||!Yd(f.command))?!0:h.every(f=>{let g=f.command?Yd(f.command):null;return g?ix(g):!0})}),l=c.length-u.length;l>0&&(n[a]=u,o.push(`Removed ${l} stale ${a} hook(s)`))}let s=this.readPluginHooks(e);if(s&&rx.every(c=>this.checkHookType(void 0,s,c))){let c=Object.values(Qn),u=l=>l!=null&&(c.some(d=>l.includes(d))||l.includes("context-mode hook"));for(let l of Object.keys(n)){let d=n[l];if(!Array.isArray(d))continue;let m=0;for(let p of d){let f=p,g=f.hooks??[],y=g.length;f.hooks=g.filter(_=>!u(_.command)),m+=y-f.hooks.length}let h=d.filter(p=>{let f=p.hooks;return Array.isArray(f)&&f.length>0});(m>0||h.length!==d.length)&&(n[l]=h,m>0&&o.push(`Removed ${m} duplicate ${l} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let i=[fr.PRE_TOOL_USE,fr.SESSION_START];for(let a of i){let c=Xd(a,e);if(a===fr.PRE_TOOL_USE){let u={matcher:tx,hooks:[{type:"command",command:c}]},l=n.PreToolUse;if(l&&Array.isArray(l)){let d=l.findIndex(m=>Oi(m,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n.PreToolUse=l}else n.PreToolUse=[u],o.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},l=n[a];if(l&&Array.isArray(l)){let d=l.findIndex(m=>Oi(m,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n[a]=l}else n[a]=[u],o.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(Qn)){let o=Pc(e,"hooks",n);try{hO(o,yO.R_OK),fO(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Sn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Tc(n,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();sx(n,JSON.stringify(o,null,2)+`
127
+ `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function eo(t,e){let r=Rc[t];return e&&r?Xe(`${e}/hooks/gemini-cli/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var Oe,cx,Rc,U4,B4,ux=S(()=>{"use strict";Cr();Oe={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},cx="mcp__(?!.*context-mode)",Rc={[Oe.BEFORE_AGENT]:"beforeagent.mjs",[Oe.BEFORE_TOOL]:"beforetool.mjs",[Oe.AFTER_TOOL]:"aftertool.mjs",[Oe.PRE_COMPRESS]:"precompress.mjs",[Oe.SESSION_START]:"sessionstart.mjs"},U4=[Oe.BEFORE_TOOL,Oe.SESSION_START],B4=[Oe.AFTER_TOOL,Oe.PRE_COMPRESS]});var px={};we(px,{GeminiCLIAdapter:()=>np});import{readFileSync as rp,writeFileSync as lx,mkdirSync as _O,accessSync as bO,chmodSync as xO,existsSync as vO,constants as SO}from"node:fs";import{resolve as Ii,join as dx}from"node:path";import{homedir as Cc}from"node:os";var np,mx=S(()=>{"use strict";pt();ux();np=class extends be{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Ii(Cc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[Oe.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:eo(Oe.BEFORE_AGENT,e)}]}],[Oe.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${cx}`,hooks:[{type:"command",command:eo(Oe.BEFORE_TOOL,e)}]}],[Oe.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:eo(Oe.AFTER_TOOL,e)}]}],[Oe.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:eo(Oe.PRE_COMPRESS,e)}]}],[Oe.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:eo(Oe.SESSION_START,e)}]}]}}readSettings(){try{let e=rp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Ii(Cc(),".gemini");_O(r,{recursive:!0}),lx(this.getSettingsPath(),JSON.stringify(e,null,2)+`
128
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[Oe.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[Oe.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}getHealthChecks(e){return Object.entries(Rc).map(([r,n])=>{let o=dx(e,"hooks","gemini-cli",n);return{name:`Hook script: ${r} (${n})`,check:()=>vO(o)?{status:"OK",detail:o}:{status:"FAIL",detail:`not found at ${o}`}}})}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(r).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=Ii(Cc(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(rp(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[],s=[{name:Oe.BEFORE_AGENT},{name:Oe.BEFORE_TOOL},{name:Oe.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:eo(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(h=>h.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[],n=dx(e,"hooks","gemini-cli");for(let o of Object.values(Rc)){let s=Ii(n,o);try{bO(s,SO.R_OK),xO(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Ii(Cc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(rp(n,"utf-8"));o.version=r,o.installPath=e,o.lastUpdated=new Date().toISOString(),lx(n,JSON.stringify(o,null,2)+`
129
+ `,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var to,J4,X4,fx=S(()=>{"use strict";to={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},J4=[to.BEFORE,to.AFTER],X4=[to.COMPACTING]});var gx={};we(gx,{OpenCodeAdapter:()=>op});import{readFileSync as hx,writeFileSync as wO,mkdirSync as EO,copyFileSync as $O,accessSync as TO,constants as PO}from"node:fs";import{resolve as Xt,join as Xr}from"node:path";import{homedir as wn}from"node:os";function kO(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var op,yx=S(()=>{"use strict";pt();fx();op=class extends be{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??Xt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Xt("kilo.json"),Xt("kilo.jsonc"),Xt(".kilo","kilo.json"),Xt(".kilo","kilo.jsonc"),Xt(".kilocode","kilo.json"),Xt(".kilocode","kilo.jsonc"),Xr(wn(),".config","kilo","kilo.json"),Xr(wn(),".config","kilo","kilo.jsonc")]:[Xt("opencode.json"),Xt("opencode.jsonc"),Xt(".opencode","opencode.json"),Xt(".opencode","opencode.jsonc"),Xr(wn(),".config","opencode","opencode.json"),Xr(wn(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Pt(),r=e?Xr(e,"context-mode","sessions"):Xr(this.getConfigDir(),"context-mode","sessions");return EO(r,{recursive:!0}),r}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Xr(wn(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Xr(wn(),".config"),Xr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[to.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(s=>s.includes(wn()))),n=null,o;for(let s of e)try{let i=hx(s,"utf-8"),a=s.endsWith(".jsonc")?kO(i):i,c=JSON.parse(a);n||(n=c,o=s);let u=r.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return n?(this.settingsPath=o,n):null}writeSettings(e){wO(this.getSettingsPath(),JSON.stringify(e,null,2)+`
130
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(n)&&r.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Xt(wn(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(hx(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],o=r.plugin??[];o.some(i=>i.includes("context-mode"))?n.push("context-mode already in plugin array"):(o.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=o;let s=r.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],n.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete r.mcp}return this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{TO(this.settingsPath,PO.R_OK);let r=this.settingsPath+".bak";return $O(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}hasLegacyContextModeMcp(e){let r=e.mcp;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var ro,o9,s9,_x=S(()=>{"use strict";ro={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},o9=[ro.TOOL_CALL_BEFORE,ro.TOOL_CALL_AFTER],s9=[ro.COMMAND_NEW]});var bx={};we(bx,{OpenClawAdapter:()=>cp});import{readFileSync as sp,writeFileSync as RO,copyFileSync as CO,accessSync as OO,constants as IO}from"node:fs";import{resolve as Yr,join as ip}from"node:path";import{homedir as ap}from"node:os";var cp,xx=S(()=>{"use strict";pt();_x();cp=class extends be{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Yr("openclaw.json")}getConfigDir(e){return Yr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return ip(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[ro.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Yr("openclaw.json"),Yr(".openclaw","openclaw.json"),ip(ap(),".openclaw","openclaw.json")];for(let r of e)try{let n=sp(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Yr("openclaw.json");RO(r,JSON.stringify(e,null,2)+`
131
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Yr(ap(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(sp(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Yr("node_modules","context-mode","package.json"),r=JSON.parse(sp(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let o=r.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Yr("openclaw.json"),Yr(".openclaw","openclaw.json"),ip(ap(),".openclaw","openclaw.json")];for(let r of e)try{OO(r,IO.R_OK);let n=r+".bak";return CO(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as vx}from"node:os";import{resolve as up}from"node:path";function Sx(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?up(vx(),t.replace(/^~[/\\]?/,"")):up(t):up(vx(),".codex")}var kx=S(()=>{"use strict"});var Px={};we(Px,{CodexAdapter:()=>pp,probeCodexCliVersion:()=>Ex});import{execFileSync as AO}from"node:child_process";import{readFileSync as ms,writeFileSync as wx,accessSync as NO,copyFileSync as DO,constants as MO,mkdirSync as lp}from"node:fs";import{resolve as jO,dirname as dp,join as no}from"node:path";import{fileURLToPath as LO}from"node:url";function Ex(t=AO){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),r=String(e).trim();return r.length>0?r:"available (version output empty)"}catch{return null}}function $x(t,e){let r=t.split(/\r?\n/),n=!1,o=[];for(let s of r){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&o.push(s)}return n?o.join(`
132
+ `):null}function Tx(t){let e=$x(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function HO(t){let e=$x(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function UO(t){if(Tx(t))return{text:t,changed:!1};let e=t.includes(`\r
131
133
  `)?`\r
132
134
  `:`
133
135
  `,r=t.split(/\r?\n/),n=r.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(n===-1){let s=t.length>0&&!t.endsWith(`
134
- `)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=r.length;for(let s=n+1;s<r.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[s]??"")){o=s;break}for(let s=n+1;s<o;s++)if(/^\s*hooks\s*=/.test(r[s]??""))return r[s]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var PC,Jn,RC,Bd,Gv=S(()=>{"use strict";yt();Tr();Hv();PC="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Jn={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},RC={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};Bd=class extends Se{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return Uv()}getSettingsPath(){return Kn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=lr(),r=e?Kn(e,"context-mode","sessions"):Kn(this.getConfigDir(),"context-mode","sessions");return Hd(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=lr(),n=r?Kn(r,"context-mode","memories"):Kn(this.getConfigDir(),"memories");return e?Kn(n,gt(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:PC,hooks:[{type:"command",command:Jn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Jn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Jn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Jn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Jn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Jn.Stop}]}]}}readSettings(){try{return{_raw_toml:Jo(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=Bv();r.push({check:"Codex CLI binary",status:n?"pass":"warn",message:n?`codex --version resolved to ${n}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...n?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{let c=Jo(this.getSettingsPath(),"utf-8"),u=Vv(c),d=!u&&CC(c);r.push({check:"Codex hooks feature flag",status:u?"pass":"fail",message:u?`[features].hooks enabled in ${this.getSettingsPath()}`:d?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...u?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let o=this.readHooksConfig();if(!o.ok)return o.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):o.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${o.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${o.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!o.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let s=this.generateHookConfig(""),i=Object.entries(s).map(([c,u])=>{let d=o.config.hooks?.[c],l=u[0],m=Array.isArray(d)&&d.some(p=>this.isExpectedHookEntry(c,p,l)),f=c==="PreCompact"?"warn":"fail";return{check:`${c} hook`,status:m?"pass":f,message:m?`${c} hook configured in ${this.getHooksPath()}`:c==="PreCompact"?`${c} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${c} hook missing or not pointing to context-mode`,fix:m?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),a=[];for(let c of Object.keys(s)){let u=o.config.hooks?.[c];if(!Array.isArray(u))continue;let d=u.filter(l=>this.isManagedContextModeEntry(c,l)).length;d>1&&a.push({check:`${c} duplicates`,status:"warn",message:`${d} context-mode entries found for ${c} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return r.concat(i,a)}checkPluginRegistration(){try{let e=Jo(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o;if(r.ok)o=r.config;else if(r.reason==="missing")o={hooks:{}};else if(r.reason==="invalid_json"){let d=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${d}`),o={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let s=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:{},i=this.generateHookConfig(e);for(let[d,l]of Object.entries(i))this.upsertManagedHookEntry(s,d,l[0],n);n.length>0&&(o.hooks=s,this.writeHooksConfig(o),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=Jo(a,"utf-8")}catch{c=""}let u=OC(c);if(u.changed){let d=u.text.includes(`\r
136
+ `)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=r.length;for(let s=n+1;s<r.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[s]??"")){o=s;break}for(let s=n+1;s<o;s++)if(/^\s*hooks\s*=/.test(r[s]??""))return r[s]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var zO,oo,FO,pp,Rx=S(()=>{"use strict";pt();Jt();kx();zO="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",oo={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},FO={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};pp=class extends be{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return Sx()}getSettingsPath(){return no(this.getConfigDir(),"config.toml")}getSessionDir(){let e=Pt(),r=e?no(e,"context-mode","sessions"):no(this.getConfigDir(),"context-mode","sessions");return lp(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=Pt(),n=r?no(r,"context-mode","memories"):no(this.getConfigDir(),"memories");return e?no(n,nt(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:zO,hooks:[{type:"command",command:oo.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:oo.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:oo.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:oo.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:oo.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:oo.Stop}]}]}}readSettings(){try{return{_raw_toml:ms(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=Ex();r.push({check:"Codex CLI binary",status:n?"pass":"warn",message:n?`codex --version resolved to ${n}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...n?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{let c=ms(this.getSettingsPath(),"utf-8"),u=Tx(c),l=!u&&HO(c);r.push({check:"Codex hooks feature flag",status:u?"pass":"fail",message:u?`[features].hooks enabled in ${this.getSettingsPath()}`:l?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...u?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let o=this.readHooksConfig();if(!o.ok)return o.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):o.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${o.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${o.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!o.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let s=this.generateHookConfig(""),i=Object.entries(s).map(([c,u])=>{let l=o.config.hooks?.[c],d=u[0],m=Array.isArray(l)&&l.some(p=>this.isExpectedHookEntry(c,p,d)),h=c==="PreCompact"?"warn":"fail";return{check:`${c} hook`,status:m?"pass":h,message:m?`${c} hook configured in ${this.getHooksPath()}`:c==="PreCompact"?`${c} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${c} hook missing or not pointing to context-mode`,fix:m?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),a=[];for(let c of Object.keys(s)){let u=o.config.hooks?.[c];if(!Array.isArray(u))continue;let l=u.filter(d=>this.isManagedContextModeEntry(c,d)).length;l>1&&a.push({check:`${c} duplicates`,status:"warn",message:`${l} context-mode entries found for ${c} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return r.concat(i,a)}checkPluginRegistration(){try{let e=ms(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o;if(r.ok)o=r.config;else if(r.reason==="missing")o={hooks:{}};else if(r.reason==="invalid_json"){let l=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${l}`),o={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let s=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:{},i=this.generateHookConfig(e);for(let[l,d]of Object.entries(i))this.upsertManagedHookEntry(s,l,d[0],n);n.length>0&&(o.hooks=s,this.writeHooksConfig(o),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=ms(a,"utf-8")}catch{c=""}let u=UO(c);if(u.changed){let l=u.text.includes(`\r
135
137
  `)?`\r
136
138
  `:`
137
- `,l=u.text.endsWith(`
138
- `)?u.text:`${u.text}${d}`;Hd(Zd(a),{recursive:!0}),Zv(a,l,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{kC(r,EC.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=$C(Zd(TC(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return Jo(e,"utf-8")}catch{return`# context-mode
139
-
140
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return Kn(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return wC(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(Jo(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();Hd(Zd(r),{recursive:!0}),Zv(r,JSON.stringify(e,null,2)+`
141
- `,"utf-8")}upsertManagedHookEntry(e,r,n,o){let s=Array.isArray(e[r])?[...e[r]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(n),e[r]=s,o.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(n)&&(s[a]=n,o.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${r} context-mode hook`);e[r]=s}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(Jn[e]??""),s=RC[e]??[];return n.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as Kv,writeFileSync as IC,mkdirSync as AC,accessSync as NC,chmodSync as DC,constants as MC}from"node:fs";import{resolve as mc,join as jC}from"node:path";var Yo,qd=S(()=>{"use strict";yt();Yo=class extends Se{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return mc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=Kv(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=Kv(mc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();AC(mc(".github","hooks"),{recursive:!0}),IC(r,JSON.stringify(e,null,2)+`
142
- `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=jC(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=mc(n,o);try{NC(s,MC.R_OK),DC(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function Jv(t,e){if(!Vd[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var qt,Vd,Zq,Bq,Yv=S(()=>{"use strict";qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Vd={[qt.PRE_TOOL_USE]:"pretooluse.mjs",[qt.POST_TOOL_USE]:"posttooluse.mjs",[qt.PRE_COMPACT]:"precompact.mjs",[qt.SESSION_START]:"sessionstart.mjs"},Zq=[qt.PRE_TOOL_USE,qt.SESSION_START],Bq=[qt.POST_TOOL_USE,qt.PRE_COMPACT]});var Qv={};Le(Qv,{VSCodeCopilotAdapter:()=>Kd});import{readFileSync as Wd,mkdirSync as Xv,accessSync as zC,existsSync as LC,constants as FC}from"node:fs";import{resolve as Xo,join as hi}from"node:path";import{homedir as Gd}from"node:os";var Kd,eb=S(()=>{"use strict";qd();yt();Yv();Kd=class extends Yo{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:qt,HOOK_SCRIPTS:Vd,buildHookCommand:Jv};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.cwd()}getSessionDir(){let e=lr();if(e){let s=hi(e,"context-mode","sessions");return Xv(s,{recursive:!0}),s}let r=Xo(".github","context-mode","sessions"),n=hi(Gd(),".vscode","context-mode","sessions"),o=LC(Xo(".github"))?r:n;return Xv(o,{recursive:!0}),o}getConfigDir(e){return Xo(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=Xo(".github","hooks");try{zC(n,FC.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=Xo(n,"context-mode.json");try{let s=Wd(o,"utf-8"),a=JSON.parse(s).hooks;a?.[qt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[qt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=Xo(".vscode","mcp.json"),r=Wd(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[hi(Gd(),".vscode","extensions"),hi(Gd(),".vscode-insiders","extensions")];for(let r of e)try{let n=Wd(hi(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function tb(t,e){if(!Jd[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Vt,Jd,Xq,Qq,rb=S(()=>{"use strict";Vt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Jd={[Vt.PRE_TOOL_USE]:"pretooluse.mjs",[Vt.POST_TOOL_USE]:"posttooluse.mjs",[Vt.PRE_COMPACT]:"precompact.mjs",[Vt.SESSION_START]:"sessionstart.mjs"},Xq=[Vt.PRE_TOOL_USE,Vt.SESSION_START],Qq=[Vt.POST_TOOL_USE,Vt.PRE_COMPACT]});var nb={};Le(nb,{JetBrainsCopilotAdapter:()=>Yd});import{readFileSync as UC}from"node:fs";import{resolve as HC}from"node:path";var Yd,ob=S(()=>{"use strict";qd();rb();Yd=class extends Yo{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Vt,HOOK_SCRIPTS:Jd,buildHookCommand:tb};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return HC(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=UC(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Vt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Vt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function gi(t,e){let r=Xd[e],n=Wt(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Wt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,Xd,ZC,BC,Qd,sb,ib,ab=S(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Xd={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},ZC="MCP:(?!ctx_)",BC=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",ZC],Qd=BC.join("|"),sb=[_e.PRE_TOOL_USE],ib=[_e.POST_TOOL_USE]});var pb={};Le(pb,{CursorAdapter:()=>ep});import{readFileSync as fc,writeFileSync as qC,mkdirSync as VC,accessSync as cb,chmodSync as WC,constants as ub,existsSync as lb,readdirSync as GC}from"node:fs";import{execSync as KC}from"node:child_process";import{resolve as Yn,join as Xn}from"node:path";import{homedir as hc}from"node:os";var db,ep,mb=S(()=>{"use strict";yt();hn();ab();db="/Library/Application Support/Cursor/hooks.json",ep=class extends Se{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return Yn(".cursor","hooks.json")}getConfigDir(e){return Yn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Wt(_e.PRE_TOOL_USE),matcher:Qd,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Wt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Wt(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Wt(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Wt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=fc(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();VC(Yn(".cursor"),{recursive:!0}),qC(r,JSON.stringify(e,null,2)+`
143
- `,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of sb){let a=s[i],c=Array.isArray(a)&&a.some(u=>gi(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of ib){let a=s[i],c=Array.isArray(a)&&a.some(u=>gi(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}lb(db)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>gi(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),r}detectPluginInstalls(){let e=[Xn(hc(),".cursor","plugins","local"),Xn(hc(),".cursor","plugins","cache")],r=[];for(let n of e){try{cb(n,ub.F_OK)}catch{continue}let o=[];try{o=GC(n)}catch{continue}for(let s of o){let i=Xn(n,s,".cursor-plugin","plugin.json");try{let a=fc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Yn(".cursor","mcp.json"),Xn(hc(),".cursor","mcp.json")];for(let n of e)try{let o=fc(n,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return KC("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},o=[];return this.upsertHookEntry(n,_e.PRE_TOOL_USE,{type:"command",command:Wt(_e.PRE_TOOL_USE),matcher:Qd,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.POST_TOOL_USE,{type:"command",command:Wt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.SESSION_START,{type:"command",command:Wt(_e.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.STOP,{type:"command",command:Wt(_e.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Wt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),r.version=1,r.hooks=n,this.writeSettings(r),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let r=[],n=Xn(e,"hooks","cursor");for(let o of Object.values(Xd)){let s=Yn(n,o);try{cb(s,ub.R_OK),WC(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),Xn(hc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(db),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=fc(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Yn(".claude","settings.json"),Yn(".claude","settings.local.json"),Xn(qe(),"settings.json")].some(r=>lb(r))}upsertHookEntry(e,r,n,o){let s=e[r],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>gi(c,r));a>=0?(i[a]=n,o.push(`Updated existing ${r} hook entry`)):(i.push(n),o.push(`Added ${r} hook entry`)),e[r]=i}}});var hb={};Le(hb,{AntigravityAdapter:()=>rp});import{readFileSync as gc,writeFileSync as JC,mkdirSync as YC}from"node:fs";import{resolve as yc,dirname as fb}from"node:path";import{fileURLToPath as XC}from"node:url";import{homedir as tp}from"node:os";var rp,gb=S(()=>{"use strict";yt();rp=class extends Se{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return yc(tp(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return yc(tp(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=gc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();YC(fb(r),{recursive:!0}),JC(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=gc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=yc(tp(),".gemini","extensions","context-mode","package.json");return JSON.parse(gc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=yc(fb(XC(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return gc(e,"utf-8")}catch{return`# context-mode
144
-
145
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function _c(t,e){let r=yb[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function Qo(t,e){let r=yb[t];return e&&r?Fe(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ue,yb,QC,eO,np,b4,x4,_b=S(()=>{"use strict";cn();Ue={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},yb={[Ue.PRE_TOOL_USE]:"pretooluse.mjs",[Ue.POST_TOOL_USE]:"posttooluse.mjs",[Ue.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ue.AGENT_SPAWN]:"agentspawn.mjs"},QC="@(?!context-mode/)",eO=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",QC],np=eO.join("|"),b4=[Ue.PRE_TOOL_USE,Ue.AGENT_SPAWN],x4=[Ue.POST_TOOL_USE,Ue.USER_PROMPT_SUBMIT]});var Sb={};Le(Sb,{KiroAdapter:()=>op});import{readFileSync as es,writeFileSync as vb,mkdirSync as bb}from"node:fs";import{resolve as Qn,dirname as xb}from"node:path";import{fileURLToPath as tO}from"node:url";import{homedir as vc}from"node:os";var op,kb=S(()=>{"use strict";yt();_b();op=class extends Se{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return Qn(vc(),".kiro","settings","mcp.json")}getConfigDir(e){return Qn(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ue.PRE_TOOL_USE]:[{matcher:np,hooks:[{type:"command",command:Qo(Ue.PRE_TOOL_USE,e)}]}],[Ue.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Qo(Ue.POST_TOOL_USE,e)}]}],[Ue.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Qo(Ue.AGENT_SPAWN,e)}]}],[Ue.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Qo(Ue.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=es(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();bb(xb(r),{recursive:!0}),vb(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=Qn(vc(),".kiro","agents","default.json");try{let s=JSON.parse(es(n,"utf-8")).hooks??{};for(let i of[Ue.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>_c(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Ue.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>_c(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=es(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=Qn(vc(),".kiro","extensions","context-mode","package.json");return JSON.parse(es(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=Qn(vc(),".kiro","agents"),o=Qn(n,"default.json");try{bb(n,{recursive:!0});let s={};try{s=JSON.parse(es(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ue.PRE_TOOL_USE,np],[Ue.POST_TOOL_USE,"*"],[Ue.AGENT_SPAWN,"*"],[Ue.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>_c(l,c))||(d.push({matcher:u,command:Qo(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${o}`))}s.hooks=i,vb(o,JSON.stringify(s,null,2),"utf-8")}catch(s){r.push(`Failed to configure hooks: ${s.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Qn(xb(tO(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return es(e,"utf-8")}catch{return`# context-mode
146
-
147
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var $b={};Le($b,{ZedAdapter:()=>ip});import{readFileSync as sp,writeFileSync as rO,mkdirSync as nO}from"node:fs";import{resolve as wb,dirname as Eb}from"node:path";import{fileURLToPath as oO}from"node:url";import{homedir as sO}from"node:os";var ip,Tb=S(()=>{"use strict";yt();ip=class extends Se{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return wb(sO(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=sp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();nO(Eb(r),{recursive:!0}),rO(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=sp(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=wb(Eb(oO(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return sp(e,"utf-8")}catch{return`# context-mode
148
-
149
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var ap,Pb=S(()=>{"use strict";ap="mcp__(?!.*context-mode)"});var Ob={};Le(Ob,{QwenCodeAdapter:()=>cp});import{readFileSync as iO,writeFileSync as aO,existsSync as cO}from"node:fs";import{resolve as Rb,join as uO}from"node:path";import{homedir as Cb}from"node:os";var cp,Ib=S(()=>{"use strict";wd();Pb();cn();cp=class extends Wo{constructor(){super([".qwen"])}name="Qwen Code";paradigm="json-stdio";projectDirEnvVar="QWEN_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getSettingsPath(){return Rb(Cb(),".qwen","settings.json")}getInstructionFiles(){return["QWEN.md"]}generateHookConfig(e){return{PreToolUse:[{matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",ap].join("|"),hooks:[{type:"command",command:Fe(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:Fe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=iO(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){aO(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;r.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(r))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(d=>{let m=d.hooks??[];return m.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?m.every(p=>{if(!p.command)return!0;let h=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?cO(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",ap].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Fe(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(m=>m.hooks?.some(p=>p.command?.includes(a))??!1);l>=0?(d[l]=u,o.push(`Updated ${i} hook`)):(d.push(u),o.push(`Added ${i} hook`)),n[i]=d}else n[i]=[u],o.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:Rb(uO(Cb(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var Ab={};Le(Ab,{OMPAdapter:()=>dp});import{readFileSync as up,writeFileSync as lO,mkdirSync as dO}from"node:fs";import{resolve as lp,dirname as pO}from"node:path";import{homedir as mO}from"node:os";var dp,Nb=S(()=>{"use strict";yt();dp=class extends Se{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??lp(mO(),".omp","agent")}getSettingsPath(){return lp(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=up(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();dO(pO(r),{recursive:!0}),lO(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=up(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:`Add context-mode to mcpServers in ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){try{let e=lp(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(up(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
150
-
151
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var Db={};Le(Db,{PiAdapter:()=>hp});import{readFileSync as pp,writeFileSync as fO,mkdirSync as hO}from"node:fs";import{resolve as mp,dirname as gO}from"node:path";import{homedir as fp}from"node:os";var hp,Mb=S(()=>{"use strict";yt();hp=class extends Se{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return mp(fp(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=pp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();hO(gO(r),{recursive:!0}),fO(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=mp(fp(),".pi","extensions","context-mode","package.json");try{return JSON.parse(pp(e,"utf-8"))?.name==="context-mode"?{check:"Pi extension registration",status:"pass",message:`context-mode extension installed at ${e}`}:{check:"Pi extension registration",status:"warn",message:`Unexpected package at ${e}`}}catch{return{check:"Pi extension registration",status:"fail",message:`context-mode not found at ${e}`,fix:"Run: context-mode upgrade"}}}getInstalledVersion(){try{let e=mp(fp(),".pi","extensions","context-mode","package.json");return JSON.parse(pp(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
152
-
153
- Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});var bc={};Le(bc,{PLATFORM_ENV_VARS:()=>ts,__resetClaudeCodePluginCacheForTests:()=>vO,__seedClaudeCodePluginCacheMissForTests:()=>bO,detectPlatform:()=>Et,foreignIdentificationEnv:()=>wO,foreignWorkspaceEnv:()=>kO,getAdapter:()=>_i,getEnvVarNames:()=>SO,getSessionDirSegments:()=>yi,workspaceEnvVarsFor:()=>gp});import{existsSync as Dt,readFileSync as yO}from"node:fs";import{resolve as wt}from"node:path";import{homedir as jb}from"node:os";function _O(){if(eo!==null)return eo!=="miss"&&eo.hasCM;try{let t=wt(jb(),".claude","plugins","installed_plugins.json"),e=yO(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return eo={hasCM:o},o}catch{return eo="miss",!1}}function vO(){eo=null}function bO(){eo="miss"}function SO(t){return(ts.get(t)??[]).map(e=>e.name)}function gp(t){return(ts.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function kO(t){let e=new Set;for(let[r,n]of ts)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function wO(t){let e=new Set;for(let[r,n]of ts)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function yi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function Et(t){if(t?.name){let n=Y_[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of ts)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&_O()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=jb();return Dt(wt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Dt(wt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Dt(wt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Dt(wt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Dt(wt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Dt(wt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Dt(wt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Dt(wt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Dt(wt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Dt(wt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Dt(wt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Dt(wt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Dt(wt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function _i(t){let e=t??Et().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Id(),Od));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(Iv(),Ov));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(Mv(),Dv));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(Lv(),zv));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(Gv(),Wv));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(eb(),Qv));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(ob(),nb));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(mb(),pb));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(gb(),hb));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(kb(),Sb));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(Tb(),$b));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(Ib(),Ob));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(Nb(),Ab));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Mb(),Db));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Id(),Od));return new r}}}var eo,xO,ts,yn=S(()=>{"use strict";X_();eo=null;xO=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],ts=new Map(xO)});import{resolve as vi}from"node:path";import{homedir as yp}from"node:os";function qe(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?vi(yp(),e.replace(/^~[/\\]?/,"")):vi(e):vi(yp(),".claude")}function EO(t=process.env){return vi(qe(t),"settings.json")}function _p(t=process.env){let e=[],r=Et();if(r.platform!=="claude-code"){let o=yi(r.platform);o&&o.length>0&&e.push(vi(yp(),...o,"settings.json"))}let n=EO(t);return e.includes(n)||e.push(n),e}var hn=S(()=>{"use strict";yn()});var Ub={};Le(Ub,{healClaudeJsonMcpArgs:()=>FO,healInstalledPlugins:()=>jO,healMcpJsonArgs:()=>LO,healPluginJsonMcpServers:()=>xc,healSettingsEnabledPlugins:()=>zO,sweepStaleMcpJson:()=>Sc});import{existsSync as Br,readFileSync as rs,writeFileSync as xi,readdirSync as NO,unlinkSync as DO,statSync as MO}from"node:fs";import{resolve as $t,sep as bi}from"node:path";function jO({registryPath:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!Br(t))return{healed:[],skipped:"no-registry"};let n;try{n=rs(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}if(!o||typeof o!="object")return{healed:[],error:"bad-shape"};let s=o.plugins&&o.plugins[r]||[];if(!Array.isArray(s)||s.length===0)return{healed:[],skipped:"no-entry"};let i=[],a=null;for(let c of s){if(!c||typeof c!="object")continue;let u=c.installPath;if(!u||typeof u!="string")continue;let d=$t(u),l=$t(e)+bi;if(!d.startsWith(l))continue;let m=$t(u,".claude-plugin","plugin.json");if(!Br(m))continue;let f=null;try{let p=JSON.parse(rs(m,"utf-8"));p&&typeof p.version=="string"&&p.version&&(f=p.version)}catch{continue}f&&(a=f,c.version!==f&&(c.version=f,i.includes("entry-version")||i.push("entry-version")))}if(a){(!o.enabledPlugins||typeof o.enabledPlugins!="object"||Array.isArray(o.enabledPlugins))&&(o.enabledPlugins={});let c=o.enabledPlugins[r];(c==null||c===!1||c==="")&&(o.enabledPlugins[r]=!0,i.push("enabled-plugins"))}if(i.length>0)try{xi(t,JSON.stringify(o,null,2)+`
154
- `,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function zO({settingsPath:t,pluginKey:e}){if(!t||!Br(t))return{healed:[],skipped:"no-settings"};let r;try{r=rs(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let n;try{n=JSON.parse(r)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!n.enabledPlugins||typeof n.enabledPlugins!="object"||Array.isArray(n.enabledPlugins))&&(n.enabledPlugins={});let s=n.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(n.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{xi(t,JSON.stringify(n,null,2)+`
155
- `,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function xc({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=$t(t),o=$t(e)+bi;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=$t(t,".claude-plugin","plugin.json");if(!Br(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=rs(s,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,f=m.map(h=>typeof h!="string"?h:Fb.test(h)&&/[/\\]start\.mjs$/.test(h)?vp:h);if(f.some((h,g)=>h!==m[g])){d.args=f,l.push("plugin-json-args");try{xi(s,JSON.stringify(a,null,2)+`
156
- `,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function LO({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=$t(t),o=$t(e)+bi;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=$t(t,".mcp.json");if(!Br(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=rs(s,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,f=m.map(h=>typeof h!="string"?h:h==="./start.mjs"||h==="start.mjs"||Fb.test(h)&&/[/\\]start\.mjs$/.test(h)?vp:h);if(f.some((h,g)=>h!==m[g])){d.args=f,l.push("mcp-json-args");try{xi(s,JSON.stringify(a,null,2)+`
157
- `,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function FO({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!Br(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=rs(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=!1;for(let c of Object.values(s))if(!(!c||typeof c!="object"||!Array.isArray(c.args)))for(let u=0;u<c.args.length;u++){let d=c.args[u];if(typeof d!="string")continue;let l=d.replace(/\\/g,"/");if(!l.startsWith(i+"/"))continue;let m=l.slice(i.length+1),f=m.indexOf("/");if(f<0)continue;let p=m.slice(f+1),h=$t(r,p);h!==d&&(c.args[u]=h,a=!0)}if(!a)return{healed:[]};try{xi(t,JSON.stringify(o,null,2),"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:["claude-json-mcp-args"]}}function Sc({pluginCacheRoot:t,pluginKey:e}){let r=[];if(!t||!e)return{removed:r,skipped:"missing-args"};let n=$t(t);if(!Br(n))return{removed:r,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:r,skipped:"bad-plugin-key"};let i=$t(n,o,s),a=n+bi;if(!i.startsWith(a))return{removed:r,skipped:"outside-cache-root"};if(!Br(i))return{removed:r,skipped:"no-plugin-dir"};let c=[];try{c=NO(i)}catch{return{removed:r,skipped:"readdir-failed"}}for(let u of c){let d=$t(i,u);if(!d.startsWith(i+bi))continue;try{if(!MO(d).isDirectory())continue}catch{continue}let l=$t(d,".mcp.json");if(Br(l))try{DO(l),r.push(l)}catch{}}return{removed:r}}var Fb,vp,bp=S(()=>{"use strict";Fb=/[/\\]context-mode-upgrade-\d+[/\\]/,vp="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,xp,j,Pr,Si=S(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(xp||(xp={}));j=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pr=t=>{switch(typeof t){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(t)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(t)?j.array:t===null?j.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?j.promise:typeof Map<"u"&&t instanceof Map?j.map:typeof Set<"u"&&t instanceof Set?j.set:typeof Date<"u"&&t instanceof Date?j.date:j.object;default:return j.unknown}}});var O,ZO,Tt,kc=S(()=>{Si();O=ce.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZO=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Tt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Tt.create=t=>new Tt(t)});var BO,qr,Sp=S(()=>{kc();Si();BO=(t,e)=>{let r;switch(t.code){case O.invalid_type:t.received===j.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case O.invalid_union:r="Invalid input";break;case O.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case O.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:r="Invalid function arguments";break;case O.invalid_return_type:r="Invalid function return type";break;case O.invalid_date:r="Invalid date";break;case O.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case O.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case O.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case O.custom:r="Invalid input";break;case O.invalid_intersection_types:r="Intersection results could not be merged";break;case O.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},qr=BO});function qO(t){Zb=t}function ns(){return Zb}var Zb,wc=S(()=>{Sp();Zb=qr});function N(t,e){let r=ns(),n=ki({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===qr?void 0:qr].filter(o=>!!o)});t.common.issues.push(n)}var ki,VO,rt,K,to,ut,Ec,$c,_n,os,kp=S(()=>{wc();Sp();ki=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},VO=[];rt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return K;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return K;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},K=Object.freeze({status:"aborted"}),to=t=>({status:"dirty",value:t}),ut=t=>({status:"valid",value:t}),Ec=t=>t.status==="aborted",$c=t=>t.status==="dirty",_n=t=>t.status==="valid",os=t=>typeof Promise<"u"&&t instanceof Promise});var Bb=S(()=>{});var H,qb=S(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(H||(H={}))});function Q(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Kb(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function uI(t){return new RegExp(`^${Kb(t)}$`)}function Jb(t){let e=`${Gb}T${Kb(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function lI(t,e){return!!((e==="v4"||!e)&&rI.test(t)||(e==="v6"||!e)&&oI.test(t))}function dI(t,e){if(!XO.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function pI(t,e){return!!((e==="v4"||!e)&&nI.test(t)||(e==="v6"||!e)&&sI.test(t))}function mI(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function ss(t){if(t instanceof Rt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Pt.create(ss(n))}return new Rt({...t._def,shape:()=>e})}else return t instanceof Gr?new Gr({...t._def,type:ss(t.element)}):t instanceof Pt?Pt.create(ss(t.unwrap())):t instanceof Cr?Cr.create(ss(t.unwrap())):t instanceof Rr?Rr.create(t.items.map(e=>ss(e))):t}function Ep(t,e){let r=Pr(t),n=Pr(e);if(t===e)return{valid:!0,data:t};if(r===j.object&&n===j.object){let o=ce.objectKeys(e),s=ce.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Ep(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===j.array&&n===j.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Ep(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===j.date&&n===j.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Yb(t,e){return new mo({values:t,typeName:I.ZodEnum,...Q(e)})}function Wb(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Xb(t,e={},r){return t?bn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Wb(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Wb(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):bn.create()}var Gt,Vb,re,WO,GO,KO,JO,YO,XO,QO,eI,tI,wp,rI,nI,oI,sI,iI,aI,Gb,cI,vn,ro,no,oo,so,is,io,ao,bn,Wr,pr,as,Gr,Rt,co,Vr,Tc,uo,Rr,Pc,cs,us,Rc,lo,po,mo,fo,xn,Kt,Pt,Cr,ho,go,ls,fI,wi,Ei,yo,hI,I,gI,Qb,ex,yI,_I,tx,vI,bI,xI,SI,kI,wI,EI,$I,TI,$p,PI,RI,CI,OI,II,AI,NI,DI,MI,jI,zI,LI,FI,UI,HI,ZI,BI,qI,VI,WI,GI,KI,JI,YI,rx=S(()=>{kc();wc();qb();kp();Si();Gt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Vb=(t,e)=>{if(_n(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Tt(t.common.issues);return this._error=r,this._error}}};re=class{get description(){return this._def.description}_getType(e){return Pr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new rt,ctx:{common:e.parent.common,data:e.data,parsedType:Pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(os(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Vb(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return _n(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>_n(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(os(o)?o:Promise.resolve(o));return Vb(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:O.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Kt({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Pt.create(this,this._def)}nullable(){return Cr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gr.create(this)}promise(){return xn.create(this,this._def)}or(e){return co.create([this,e],this._def)}and(e){return uo.create(this,e,this._def)}transform(e){return new Kt({...Q(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ho({...Q(this._def),innerType:this,defaultValue:r,typeName:I.ZodDefault})}brand(){return new wi({typeName:I.ZodBranded,type:this,...Q(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new go({...Q(this._def),innerType:this,catchValue:r,typeName:I.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ei.create(this,e)}readonly(){return yo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},WO=/^c[^\s-]{8,}$/i,GO=/^[0-9a-z]+$/,KO=/^[0-9A-HJKMNP-TV-Z]{26}$/i,JO=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,YO=/^[a-z0-9_-]{21}$/i,XO=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QO=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,eI=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rI=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,nI=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,oI=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,sI=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,iI=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aI=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gb="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",cI=new RegExp(`^${Gb}$`);vn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_type,expected:j.string,received:s.parsedType}),K}let n=new rt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?N(o,{code:O.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&N(o,{code:O.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")eI.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"email",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")wp||(wp=new RegExp(tI,"u")),wp.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"emoji",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")JO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"uuid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")YO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"nanoid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")WO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")GO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid2",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")KO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"ulid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),N(o,{validation:"url",code:O.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"regex",code:O.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Jb(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?cI.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?uI(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?QO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"duration",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?lI(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"ip",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?dI(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"jwt",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?pI(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cidr",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?iI.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?aI.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64url",code:O.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:O.invalid_string,...H.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...H.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...H.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...H.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...H.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...H.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...H.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...H.errToObj(r)})}nonempty(e){return this.min(1,H.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};vn.create=t=>new vn({checks:[],typeName:I.ZodString,coerce:t?.coerce??!1,...Q(t)});ro=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==j.number){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_type,expected:j.number,received:s.parsedType}),K}let n,o=new rt;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?mI(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,H.toString(r))}gt(e,r){return this.setLimit("min",e,!1,H.toString(r))}lte(e,r){return this.setLimit("max",e,!0,H.toString(r))}lt(e,r){return this.setLimit("max",e,!1,H.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:H.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:H.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};ro.create=t=>new ro({checks:[],typeName:I.ZodNumber,coerce:t?.coerce||!1,...Q(t)});no=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==j.bigint)return this._getInvalidInput(e);let n,o=new rt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:j.bigint,received:r.parsedType}),K}gte(e,r){return this.setLimit("min",e,!0,H.toString(r))}gt(e,r){return this.setLimit("min",e,!1,H.toString(r))}lte(e,r){return this.setLimit("max",e,!0,H.toString(r))}lt(e,r){return this.setLimit("max",e,!1,H.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:H.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};no.create=t=>new no({checks:[],typeName:I.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});oo=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.boolean,received:n.parsedType}),K}return ut(e.data)}};oo.create=t=>new oo({typeName:I.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});so=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_type,expected:j.date,received:s.parsedType}),K}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_date}),K}let n=new rt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:H.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:H.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};so.create=t=>new so({checks:[],coerce:t?.coerce||!1,typeName:I.ZodDate,...Q(t)});is=class extends re{_parse(e){if(this._getType(e)!==j.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.symbol,received:n.parsedType}),K}return ut(e.data)}};is.create=t=>new is({typeName:I.ZodSymbol,...Q(t)});io=class extends re{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.undefined,received:n.parsedType}),K}return ut(e.data)}};io.create=t=>new io({typeName:I.ZodUndefined,...Q(t)});ao=class extends re{_parse(e){if(this._getType(e)!==j.null){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.null,received:n.parsedType}),K}return ut(e.data)}};ao.create=t=>new ao({typeName:I.ZodNull,...Q(t)});bn=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return ut(e.data)}};bn.create=t=>new bn({typeName:I.ZodAny,...Q(t)});Wr=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ut(e.data)}};Wr.create=t=>new Wr({typeName:I.ZodUnknown,...Q(t)});pr=class extends re{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:j.never,received:r.parsedType}),K}};pr.create=t=>new pr({typeName:I.ZodNever,...Q(t)});as=class extends re{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.void,received:n.parsedType}),K}return ut(e.data)}};as.create=t=>new as({typeName:I.ZodVoid,...Q(t)});Gr=class t extends re{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==j.array)return N(r,{code:O.invalid_type,expected:j.array,received:r.parsedType}),K;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(N(r,{code:i?O.too_big:O.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(N(r,{code:O.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(N(r,{code:O.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Gt(r,i,r.path,a)))).then(i=>rt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Gt(r,i,r.path,a)));return rt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:H.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:H.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:H.toString(r)}})}nonempty(e){return this.min(1,e)}};Gr.create=(t,e)=>new Gr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...Q(e)});Rt=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==j.object){let u=this._getOrReturnCtx(e);return N(u,{code:O.invalid_type,expected:j.object,received:u.parsedType}),K}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof pr&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=s[u],l=o.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Gt(o,l,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof pr){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")a.length>0&&(N(o,{code:O.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=o.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Gt(o,l,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,m=await d.value;u.push({key:l,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>rt.mergeObjectSync(n,u)):rt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return H.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:H.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:I.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ce.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ss(this)}partial(e){let r={};for(let n of ce.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Pt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Yb(ce.objectKeys(this.shape))}};Rt.create=(t,e)=>new Rt({shape:()=>t,unknownKeys:"strip",catchall:pr.create(),typeName:I.ZodObject,...Q(e)});Rt.strictCreate=(t,e)=>new Rt({shape:()=>t,unknownKeys:"strict",catchall:pr.create(),typeName:I.ZodObject,...Q(e)});Rt.lazycreate=(t,e)=>new Rt({shape:t,unknownKeys:"strip",catchall:pr.create(),typeName:I.ZodObject,...Q(e)});co=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Tt(a.ctx.common.issues));return N(r,{code:O.invalid_union,unionErrors:i}),K}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Tt(c));return N(r,{code:O.invalid_union,unionErrors:a}),K}}get options(){return this._def.options}};co.create=(t,e)=>new co({options:t,typeName:I.ZodUnion,...Q(e)});Vr=t=>t instanceof lo?Vr(t.schema):t instanceof Kt?Vr(t.innerType()):t instanceof po?[t.value]:t instanceof mo?t.options:t instanceof fo?ce.objectValues(t.enum):t instanceof ho?Vr(t._def.innerType):t instanceof io?[void 0]:t instanceof ao?[null]:t instanceof Pt?[void 0,...Vr(t.unwrap())]:t instanceof Cr?[null,...Vr(t.unwrap())]:t instanceof wi||t instanceof yo?Vr(t.unwrap()):t instanceof go?Vr(t._def.innerType):[],Tc=class t extends re{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.object)return N(r,{code:O.invalid_type,expected:j.object,received:r.parsedType}),K;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(N(r,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Vr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:I.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...Q(n)})}};uo=class extends re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ec(s)||Ec(i))return K;let a=Ep(s.value,i.value);return a.valid?(($c(s)||$c(i))&&r.dirty(),{status:r.value,value:a.data}):(N(n,{code:O.invalid_intersection_types}),K)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};uo.create=(t,e,r)=>new uo({left:t,right:e,typeName:I.ZodIntersection,...Q(r)});Rr=class t extends re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return N(n,{code:O.invalid_type,expected:j.array,received:n.parsedType}),K;if(n.data.length<this._def.items.length)return N(n,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&n.data.length>this._def.items.length&&(N(n,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Gt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>rt.mergeArray(r,i)):rt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Rr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rr({items:t,typeName:I.ZodTuple,rest:null,...Q(e)})};Pc=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.object)return N(n,{code:O.invalid_type,expected:j.object,received:n.parsedType}),K;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Gt(n,a,n.path,a)),value:i._parse(new Gt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?rt.mergeObjectAsync(r,o):rt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof re?new t({keyType:e,valueType:r,typeName:I.ZodRecord,...Q(n)}):new t({keyType:vn.create(),valueType:e,typeName:I.ZodRecord,...Q(r)})}},cs=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.map)return N(n,{code:O.invalid_type,expected:j.map,received:n.parsedType}),K;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Gt(n,a,n.path,[u,"key"])),value:s._parse(new Gt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return K;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return K;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};cs.create=(t,e,r)=>new cs({valueType:e,keyType:t,typeName:I.ZodMap,...Q(r)});us=class t extends re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return N(n,{code:O.invalid_type,expected:j.set,received:n.parsedType}),K;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(N(n,{code:O.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(N(n,{code:O.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return K;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Gt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:H.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:H.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};us.create=(t,e)=>new us({valueType:t,minSize:null,maxSize:null,typeName:I.ZodSet,...Q(e)});Rc=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.function)return N(r,{code:O.invalid_type,expected:j.function,received:r.parsedType}),K;function n(a,c){return ki({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ns(),qr].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:c}})}function o(a,c){return ki({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ns(),qr].filter(u=>!!u),issueData:{code:O.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof xn){let a=this;return ut(async function(...c){let u=new Tt([]),d=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,s).catch(f=>{throw u.addIssue(o(l,f)),u})})}else{let a=this;return ut(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Tt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,s);if(!l.success)throw new Tt([o(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Rr.create(e).rest(Wr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Rr.create([]).rest(Wr.create()),returns:r||Wr.create(),typeName:I.ZodFunction,...Q(n)})}},lo=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};lo.create=(t,e)=>new lo({getter:t,typeName:I.ZodLazy,...Q(e)});po=class extends re{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return N(r,{received:r.data,code:O.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};po.create=(t,e)=>new po({value:t,typeName:I.ZodLiteral,...Q(e)});mo=class t extends re{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ce.joinValues(n),received:r.parsedType,code:O.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{received:r.data,code:O.invalid_enum_value,options:n}),K}return ut(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};mo.create=Yb;fo=class extends re{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let o=ce.objectValues(r);return N(n,{expected:ce.joinValues(o),received:n.parsedType,code:O.invalid_type}),K}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(r);return N(n,{received:n.data,code:O.invalid_enum_value,options:o}),K}return ut(e.data)}get enum(){return this._def.values}};fo.create=(t,e)=>new fo({values:t,typeName:I.ZodNativeEnum,...Q(e)});xn=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.promise&&r.common.async===!1)return N(r,{code:O.invalid_type,expected:j.promise,received:r.parsedType}),K;let n=r.parsedType===j.promise?r.data:Promise.resolve(r.data);return ut(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};xn.create=(t,e)=>new xn({type:t,typeName:I.ZodPromise,...Q(e)});Kt=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{N(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return K;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?K:c.status==="dirty"?to(c.value):r.value==="dirty"?to(c.value):c});{if(r.value==="aborted")return K;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?K:a.status==="dirty"?to(a.value):r.value==="dirty"?to(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?K:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?K:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_n(i))return K;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>_n(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):K);ce.assertNever(o)}};Kt.create=(t,e,r)=>new Kt({schema:t,typeName:I.ZodEffects,effect:e,...Q(r)});Kt.createWithPreprocess=(t,e,r)=>new Kt({schema:e,effect:{type:"preprocess",transform:t},typeName:I.ZodEffects,...Q(r)});Pt=class extends re{_parse(e){return this._getType(e)===j.undefined?ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Pt.create=(t,e)=>new Pt({innerType:t,typeName:I.ZodOptional,...Q(e)});Cr=class extends re{_parse(e){return this._getType(e)===j.null?ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Cr.create=(t,e)=>new Cr({innerType:t,typeName:I.ZodNullable,...Q(e)});ho=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ho.create=(t,e)=>new ho({innerType:t,typeName:I.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});go=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return os(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Tt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Tt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};go.create=(t,e)=>new go({innerType:t,typeName:I.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});ls=class extends re{_parse(e){if(this._getType(e)!==j.nan){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.nan,received:n.parsedType}),K}return{status:"valid",value:e.data}}};ls.create=t=>new ls({typeName:I.ZodNaN,...Q(t)});fI=Symbol("zod_brand"),wi=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ei=class t extends re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?K:s.status==="dirty"?(r.dirty(),to(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?K:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:I.ZodPipeline})}},yo=class extends re{_parse(e){let r=this._def.innerType._parse(e),n=o=>(_n(o)&&(o.value=Object.freeze(o.value)),o);return os(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};yo.create=(t,e)=>new yo({innerType:t,typeName:I.ZodReadonly,...Q(e)});hI={object:Rt.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(I||(I={}));gI=(t,e={message:`Input not instance of ${t.name}`})=>Xb(r=>r instanceof t,e),Qb=vn.create,ex=ro.create,yI=ls.create,_I=no.create,tx=oo.create,vI=so.create,bI=is.create,xI=io.create,SI=ao.create,kI=bn.create,wI=Wr.create,EI=pr.create,$I=as.create,TI=Gr.create,$p=Rt.create,PI=Rt.strictCreate,RI=co.create,CI=Tc.create,OI=uo.create,II=Rr.create,AI=Pc.create,NI=cs.create,DI=us.create,MI=Rc.create,jI=lo.create,zI=po.create,LI=mo.create,FI=fo.create,UI=xn.create,HI=Kt.create,ZI=Pt.create,BI=Cr.create,qI=Kt.createWithPreprocess,VI=Ei.create,WI=()=>Qb().optional(),GI=()=>ex().optional(),KI=()=>tx().optional(),JI={string:(t=>vn.create({...t,coerce:!0})),number:(t=>ro.create({...t,coerce:!0})),boolean:(t=>oo.create({...t,coerce:!0})),bigint:(t=>no.create({...t,coerce:!0})),date:(t=>so.create({...t,coerce:!0}))},YI=K});var D={};Le(D,{BRAND:()=>fI,DIRTY:()=>to,EMPTY_PATH:()=>VO,INVALID:()=>K,NEVER:()=>YI,OK:()=>ut,ParseStatus:()=>rt,Schema:()=>re,ZodAny:()=>bn,ZodArray:()=>Gr,ZodBigInt:()=>no,ZodBoolean:()=>oo,ZodBranded:()=>wi,ZodCatch:()=>go,ZodDate:()=>so,ZodDefault:()=>ho,ZodDiscriminatedUnion:()=>Tc,ZodEffects:()=>Kt,ZodEnum:()=>mo,ZodError:()=>Tt,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>Rc,ZodIntersection:()=>uo,ZodIssueCode:()=>O,ZodLazy:()=>lo,ZodLiteral:()=>po,ZodMap:()=>cs,ZodNaN:()=>ls,ZodNativeEnum:()=>fo,ZodNever:()=>pr,ZodNull:()=>ao,ZodNullable:()=>Cr,ZodNumber:()=>ro,ZodObject:()=>Rt,ZodOptional:()=>Pt,ZodParsedType:()=>j,ZodPipeline:()=>Ei,ZodPromise:()=>xn,ZodReadonly:()=>yo,ZodRecord:()=>Pc,ZodSchema:()=>re,ZodSet:()=>us,ZodString:()=>vn,ZodSymbol:()=>is,ZodTransformer:()=>Kt,ZodTuple:()=>Rr,ZodType:()=>re,ZodUndefined:()=>io,ZodUnion:()=>co,ZodUnknown:()=>Wr,ZodVoid:()=>as,addIssueToContext:()=>N,any:()=>kI,array:()=>TI,bigint:()=>_I,boolean:()=>tx,coerce:()=>JI,custom:()=>Xb,date:()=>vI,datetimeRegex:()=>Jb,defaultErrorMap:()=>qr,discriminatedUnion:()=>CI,effect:()=>HI,enum:()=>LI,function:()=>MI,getErrorMap:()=>ns,getParsedType:()=>Pr,instanceof:()=>gI,intersection:()=>OI,isAborted:()=>Ec,isAsync:()=>os,isDirty:()=>$c,isValid:()=>_n,late:()=>hI,lazy:()=>jI,literal:()=>zI,makeIssue:()=>ki,map:()=>NI,nan:()=>yI,nativeEnum:()=>FI,never:()=>EI,null:()=>SI,nullable:()=>BI,number:()=>ex,object:()=>$p,objectUtil:()=>xp,oboolean:()=>KI,onumber:()=>GI,optional:()=>ZI,ostring:()=>WI,pipeline:()=>VI,preprocess:()=>qI,promise:()=>UI,quotelessJson:()=>ZO,record:()=>AI,set:()=>DI,setErrorMap:()=>qO,strictObject:()=>PI,string:()=>Qb,symbol:()=>bI,transformer:()=>HI,tuple:()=>II,undefined:()=>xI,union:()=>RI,unknown:()=>wI,util:()=>ce,void:()=>$I});var Cc=S(()=>{wc();kp();Bb();Si();rx();kc()});var $i=S(()=>{Cc()});function T(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Mt(t){return t&&Object.assign(Oc,t),Oc}var QI,Kr,Oc,ds=S(()=>{QI=Object.freeze({status:"aborted"});Kr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Oc={}});var ue={};Le(ue,{BIGINT_FORMAT_RANGES:()=>ox,Class:()=>Pp,NUMBER_FORMAT_RANGES:()=>Dp,aborted:()=>vo,allowsEval:()=>Ip,assert:()=>oA,assertEqual:()=>eA,assertIs:()=>rA,assertNever:()=>nA,assertNotEqual:()=>tA,assignProp:()=>Op,cached:()=>Ri,captureStackTrace:()=>Ac,cleanEnum:()=>yA,cleanRegex:()=>Oi,clone:()=>jt,createTransparentProxy:()=>lA,defineLazy:()=>ke,esc:()=>_o,escapeRegex:()=>Sn,extend:()=>mA,finalizeIssue:()=>mr,floatSafeRemainder:()=>Cp,getElementAtPath:()=>sA,getEnumValues:()=>Pi,getLengthableOrigin:()=>Ii,getParsedType:()=>uA,getSizableOrigin:()=>sx,isObject:()=>ps,isPlainObject:()=>ms,issue:()=>Mp,joinValues:()=>Ic,jsonStringifyReplacer:()=>Rp,merge:()=>fA,normalizeParams:()=>J,nullish:()=>Ci,numKeys:()=>cA,omit:()=>pA,optionalKeys:()=>Np,partial:()=>hA,pick:()=>dA,prefixIssues:()=>Or,primitiveTypes:()=>nx,promiseAllObject:()=>iA,propertyKeyTypes:()=>Ap,randomString:()=>aA,required:()=>gA,stringifyPrimitive:()=>Nc,unwrapMessage:()=>Ti});function eA(t){return t}function tA(t){return t}function rA(t){}function nA(t){throw new Error}function oA(t){}function Pi(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ic(t,e="|"){return t.map(r=>Nc(r)).join(e)}function Rp(t,e){return typeof e=="bigint"?e.toString():e}function Ri(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ci(t){return t==null}function Oi(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Cp(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function ke(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Op(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function sA(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function iA(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function aA(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function _o(t){return JSON.stringify(t)}function ps(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ms(t){if(ps(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(ps(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cA(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Sn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function J(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function lA(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Nc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Np(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function dA(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return jt(t,{...t._zod.def,shape:r,checks:[]})}function pA(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return jt(t,{...t._zod.def,shape:r,checks:[]})}function mA(t,e){if(!ms(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Op(this,"shape",n),n},checks:[]};return jt(t,r)}function fA(t,e){return jt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Op(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function hA(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return jt(e,{...e._zod.def,shape:o,checks:[]})}function gA(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return jt(e,{...e._zod.def,shape:o,checks:[]})}function vo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Or(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ti(t){return typeof t=="string"?t:t?.message}function mr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ti(t.inst?._zod.def?.error?.(t))??Ti(e?.error?.(t))??Ti(r.customError?.(t))??Ti(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function sx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ii(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Mp(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function yA(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ac,Ip,uA,Ap,nx,Dp,ox,Pp,Ir=S(()=>{Ac=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Ip=Ri(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});uA=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Ap=new Set(["string","number","symbol"]),nx=new Set(["string","number","bigint","boolean","symbol","undefined"]);Dp={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ox={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Pp=class{constructor(...e){}}});function jp(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function zp(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var ix,Dc,Ai,Lp=S(()=>{ds();Ir();ix=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Rp,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Dc=T("$ZodError",ix),Ai=T("$ZodError",ix,{Parent:Error})});var Fp,Up,Hp,Zp,Bp,bo,qp,xo,Vp=S(()=>{ds();Lp();Ir();Fp=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Kr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>mr(c,s,Mt())));throw Ac(a,o?.callee),a}return i.value},Up=Fp(Ai),Hp=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>mr(c,s,Mt())));throw Ac(a,o?.callee),a}return i.value},Zp=Hp(Ai),Bp=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Kr;return s.issues.length?{success:!1,error:new(t??Dc)(s.issues.map(i=>mr(i,o,Mt())))}:{success:!0,data:s.value}},bo=Bp(Ai),qp=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>mr(i,o,Mt())))}:{success:!0,data:s.value}},xo=qp(Ai)});function gx(){return new RegExp(vA,"u")}function $x(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Tx(t){return new RegExp(`^${$x(t)}$`)}function Px(t){let e=$x({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${wx}T(?:${n})$`)}var ax,cx,ux,lx,dx,px,mx,fx,Wp,hx,vA,yx,_x,vx,bx,xx,Gp,Sx,kx,wx,Ex,Rx,Cx,Ox,Ix,Ax,Nx,Dx,jc=S(()=>{ax=/^[cC][^\s-]{8,}$/,cx=/^[0-9a-z]+$/,ux=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lx=/^[0-9a-vA-V]{20}$/,dx=/^[A-Za-z0-9]{27}$/,px=/^[a-zA-Z0-9_-]{21}$/,mx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fx=/^([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})$/,Wp=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,hx=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";yx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_x=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,vx=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bx=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Gp=/^[A-Za-z0-9_-]*$/,Sx=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,kx=/^\+(?:[0-9]){6,14}[0-9]$/,wx="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ex=new RegExp(`^${wx}$`);Rx=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Cx=/^\d+$/,Ox=/^-?\d+(?:\.\d+)?/i,Ix=/true|false/i,Ax=/null/i,Nx=/^[^A-Z]*$/,Dx=/^[^a-z]*$/});var nt,Mx,Kp,Jp,jx,zx,Lx,Fx,Ux,Ni,Hx,Zx,Bx,qx,Vx,Wx,Gx,zc=S(()=>{ds();jc();Ir();nt=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Mx={number:"number",bigint:"bigint",object:"date"},Kp=T("$ZodCheckLessThan",(t,e)=>{nt.init(t,e);let r=Mx[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Jp=T("$ZodCheckGreaterThan",(t,e)=>{nt.init(t,e);let r=Mx[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),jx=T("$ZodCheckMultipleOf",(t,e)=>{nt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Cp(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),zx=T("$ZodCheckNumberFormat",(t,e)=>{nt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Dp[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Cx)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Lx=T("$ZodCheckMaxLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ci(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Ii(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Fx=T("$ZodCheckMinLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ci(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ii(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ux=T("$ZodCheckLengthEquals",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ci(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ii(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ni=T("$ZodCheckStringFormat",(t,e)=>{var r,n;nt.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Hx=T("$ZodCheckRegex",(t,e)=>{Ni.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Zx=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Nx),Ni.init(t,e)}),Bx=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Dx),Ni.init(t,e)}),qx=T("$ZodCheckIncludes",(t,e)=>{nt.init(t,e);let r=Sn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Vx=T("$ZodCheckStartsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`^${Sn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Wx=T("$ZodCheckEndsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`.*${Sn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Gx=T("$ZodCheckOverwrite",(t,e)=>{nt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Lc,Yp=S(()=>{Lc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
158
- `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
159
- `))}}});var Jx,Xp=S(()=>{Jx={major:4,minor:0,patch:0}});function lS(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function bA(t){if(!Gp.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return lS(r)}function xA(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function Yx(t,e,r){t.issues.length&&e.issues.push(...Or(r,t.issues)),e.value[r]=t.value}function Fc(t,e,r){t.issues.length&&e.issues.push(...Or(r,t.issues)),e.value[r]=t.value}function Xx(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Or(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Qx(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>mr(s,n,Mt())))}),e}function Qp(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ms(t)&&ms(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Qp(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Qp(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function eS(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),vo(t))return t;let n=Qp(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function tS(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function rS(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function nS(t,e,r){return vo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function oS(t){return t.value=Object.freeze(t.value),t}function sS(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Mp(o))}}var ve,Di,we,em,tm,rm,nm,om,sm,im,am,cm,um,lm,iS,aS,cS,uS,dm,pm,mm,fm,hm,gm,ym,_m,Uc,vm,bm,xm,Sm,km,wm,Hc,Zc,Em,$m,Tm,Pm,Rm,Cm,Om,Im,Am,Nm,Dm,Mm,jm,zm,Lm,dS=S(()=>{zc();ds();Yp();Vp();jc();Ir();Xp();Ir();ve=T("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Jx;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=vo(s),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let l=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new Kr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==l&&(c||(c=vo(s,l)))});else{if(s.issues.length===l)continue;c||(c=vo(s,l))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Kr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=bo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return xo(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Di=T("$ZodString",(t,e)=>{ve.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Rx(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),we=T("$ZodStringFormat",(t,e)=>{Ni.init(t,e),Di.init(t,e)}),em=T("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=fx),we.init(t,e)}),tm=T("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Wp(n))}else e.pattern??(e.pattern=Wp());we.init(t,e)}),rm=T("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=hx),we.init(t,e)}),nm=T("$ZodURL",(t,e)=>{we.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Sx.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),om=T("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=gx()),we.init(t,e)}),sm=T("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=px),we.init(t,e)}),im=T("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ax),we.init(t,e)}),am=T("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=cx),we.init(t,e)}),cm=T("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ux),we.init(t,e)}),um=T("$ZodXID",(t,e)=>{e.pattern??(e.pattern=lx),we.init(t,e)}),lm=T("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=dx),we.init(t,e)}),iS=T("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Px(e)),we.init(t,e)}),aS=T("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ex),we.init(t,e)}),cS=T("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Tx(e)),we.init(t,e)}),uS=T("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=mx),we.init(t,e)}),dm=T("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=yx),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),pm=T("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=_x),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),mm=T("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=vx),we.init(t,e)}),fm=T("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=bx),we.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});hm=T("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=xx),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{lS(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});gm=T("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Gp),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{bA(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),ym=T("$ZodE164",(t,e)=>{e.pattern??(e.pattern=kx),we.init(t,e)});_m=T("$ZodJWT",(t,e)=>{we.init(t,e),t._zod.check=r=>{xA(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Uc=T("$ZodNumber",(t,e)=>{ve.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ox,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),vm=T("$ZodNumber",(t,e)=>{zx.init(t,e),Uc.init(t,e)}),bm=T("$ZodBoolean",(t,e)=>{ve.init(t,e),t._zod.pattern=Ix,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),xm=T("$ZodNull",(t,e)=>{ve.init(t,e),t._zod.pattern=Ax,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Sm=T("$ZodUnknown",(t,e)=>{ve.init(t,e),t._zod.parse=r=>r}),km=T("$ZodNever",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});wm=T("$ZodArray",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Yx(u,r,i))):Yx(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Hc=T("$ZodObject",(t,e)=>{ve.init(t,e);let r=Ri(()=>{let l=Object.keys(e.shape);for(let f of l)if(!(e.shape[f]instanceof ve))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let m=Np(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(m)}});ke(t._zod,"propValues",()=>{let l=e.shape,m={};for(let f in l){let p=l[f]._zod;if(p.values){m[f]??(m[f]=new Set);for(let h of p.values)m[f].add(h)}}return m});let n=l=>{let m=new Lc(["shape","payload","ctx"]),f=r.value,p=v=>{let _=_o(v);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};m.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of f.keys)h[v]=`key_${g++}`;m.write("const newResult = {}");for(let v of f.keys)if(f.optionalKeys.has(v)){let _=h[v];m.write(`const ${_} = ${p(v)};`);let b=_o(v);m.write(`
160
- if (${_}.issues.length) {
161
- if (input[${b}] === undefined) {
162
- if (${b} in input) {
163
- newResult[${b}] = undefined;
164
- }
165
- } else {
166
- payload.issues = payload.issues.concat(
167
- ${_}.issues.map((iss) => ({
168
- ...iss,
169
- path: iss.path ? [${b}, ...iss.path] : [${b}],
170
- }))
171
- );
172
- }
173
- } else if (${_}.value === undefined) {
174
- if (${b} in input) newResult[${b}] = undefined;
175
- } else {
176
- newResult[${b}] = ${_}.value;
177
- }
178
- `)}else{let _=h[v];m.write(`const ${_} = ${p(v)};`),m.write(`
179
- if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
180
- ...iss,
181
- path: iss.path ? [${_o(v)}, ...iss.path] : [${_o(v)}]
182
- })));`),m.write(`newResult[${_o(v)}] = ${_}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(v,_)=>y(l,v,_)},o,s=ps,i=!Oc.jitless,c=i&&Ip.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let f=l.value;if(!s(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),l=o(l,m);else{l.value={};let _=d.shape;for(let b of d.keys){let x=_[b],P=x._zod.run({value:f[b],issues:[]},m),E=x._zod.optin==="optional"&&x._zod.optout==="optional";P instanceof Promise?p.push(P.then(R=>E?Xx(R,l,b,f):Fc(R,l,b))):E?Xx(P,l,b,f):Fc(P,l,b)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let h=[],g=d.keySet,y=u._zod,v=y.def.type;for(let _ of Object.keys(f)){if(g.has(_))continue;if(v==="never"){h.push(_);continue}let b=y.run({value:f[_],issues:[]},m);b instanceof Promise?p.push(b.then(x=>Fc(x,l,_))):Fc(b,l,_)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Zc=T("$ZodUnion",(t,e)=>{ve.init(t,e),ke(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ke(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Oi(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Qx(i,r,t,n)):Qx(s,r,t,n)}}),Em=T("$ZodDiscriminatedUnion",(t,e)=>{Zc.init(t,e);let r=t._zod.parse;ke(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Ri(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!ps(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),$m=T("$ZodIntersection",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>eS(r,c,u)):eS(r,s,i)}});Tm=T("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ms(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Or(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...Or(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>mr(u,n,Mt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Or(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Or(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Pm=T("$ZodEnum",(t,e)=>{ve.init(t,e);let r=Pi(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ap.has(typeof n)).map(n=>typeof n=="string"?Sn(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Rm=T("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Sn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Cm=T("$ZodTransform",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Kr;return r.value=o,r}}),Om=T("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Oi(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Im=T("$ZodNullable",(t,e)=>{ve.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Oi(r.source)}|null)$`):void 0}),ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Am=T("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>tS(s,e)):tS(o,e)}});Nm=T("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Dm=T("$ZodNonOptional",(t,e)=>{ve.init(t,e),ke(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>rS(s,t)):rS(o,t)}});Mm=T("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>mr(i,n,Mt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>mr(s,n,Mt()))},input:r.value}),r.issues=[]),r)}}),jm=T("$ZodPipe",(t,e)=>{ve.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>nS(s,e,n)):nS(o,e,n)}});zm=T("$ZodReadonly",(t,e)=>{ve.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(oS):oS(o)}});Lm=T("$ZodCustom",(t,e)=>{nt.init(t,e),ve.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>sS(s,r,n,t));sS(o,r,n,t)}})});function pS(){return{localeError:kA()}}var SA,kA,mS=S(()=>{Ir();SA=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},kA=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${SA(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Nc(n.values[0])}`:`Invalid option: expected one of ${Ic(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ic(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Bc=S(()=>{});function fS(){return new Mi}var Mi,kn,Um=S(()=>{Mi=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};kn=fS()});function Hm(t,e){return new t({type:"string",...J(e)})}function Zm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function qc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function Bm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function qm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function Vm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function Wm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function Gm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function Km(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function Jm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function Ym(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function Xm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function Qm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function ef(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function tf(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function rf(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function nf(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function of(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function sf(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function af(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function cf(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function uf(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function lf(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function hS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function gS(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function yS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function _S(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function df(t,e){return new t({type:"number",checks:[],...J(e)})}function pf(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function mf(t,e){return new t({type:"boolean",...J(e)})}function ff(t,e){return new t({type:"null",...J(e)})}function hf(t){return new t({type:"unknown"})}function gf(t,e){return new t({type:"never",...J(e)})}function Vc(t,e){return new Kp({check:"less_than",...J(e),value:t,inclusive:!1})}function ji(t,e){return new Kp({check:"less_than",...J(e),value:t,inclusive:!0})}function Wc(t,e){return new Jp({check:"greater_than",...J(e),value:t,inclusive:!1})}function zi(t,e){return new Jp({check:"greater_than",...J(e),value:t,inclusive:!0})}function Gc(t,e){return new jx({check:"multiple_of",...J(e),value:t})}function Kc(t,e){return new Lx({check:"max_length",...J(e),maximum:t})}function fs(t,e){return new Fx({check:"min_length",...J(e),minimum:t})}function Jc(t,e){return new Ux({check:"length_equals",...J(e),length:t})}function yf(t,e){return new Hx({check:"string_format",format:"regex",...J(e),pattern:t})}function _f(t){return new Zx({check:"string_format",format:"lowercase",...J(t)})}function vf(t){return new Bx({check:"string_format",format:"uppercase",...J(t)})}function bf(t,e){return new qx({check:"string_format",format:"includes",...J(e),includes:t})}function xf(t,e){return new Vx({check:"string_format",format:"starts_with",...J(e),prefix:t})}function Sf(t,e){return new Wx({check:"string_format",format:"ends_with",...J(e),suffix:t})}function So(t){return new Gx({check:"overwrite",tx:t})}function kf(t){return So(e=>e.normalize(t))}function wf(){return So(t=>t.trim())}function Ef(){return So(t=>t.toLowerCase())}function $f(){return So(t=>t.toUpperCase())}function vS(t,e,r){return new t({type:"array",element:e,...J(r)})}function Tf(t,e,r){let n=J(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Pf(t,e,r){return new t({type:"custom",check:"custom",fn:e,...J(r)})}var bS=S(()=>{zc();Ir()});var xS=S(()=>{});function Rf(t,e){if(t instanceof Mi){let n=new Yc(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Yc(e);return r.process(t),r.emit(t,e)}function Je(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Je(o.element,r);case"object":{for(let s in o.shape)if(Je(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Je(s,r))return!0;return!1}case"intersection":return Je(o.left,r)||Je(o.right,r);case"tuple":{for(let s of o.items)if(Je(s,r))return!0;return!!(o.rest&&Je(o.rest,r))}case"record":return Je(o.keyType,r)||Je(o.valueType,r);case"map":return Je(o.keyType,r)||Je(o.valueType,r);case"set":return Je(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Je(o.innerType,r);case"lazy":return Je(o.getter(),r);case"default":return Je(o.innerType,r);case"prefault":return Je(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Je(o.in,r)||Je(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Yc,SS=S(()=>{Um();Ir();Yc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??kn,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,l),this.seen.get(m).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let p=f;p.type="string";let{minimum:h,maximum:g,format:y,patterns:v,contentEncoding:_}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),v&&v.size>0){let b=[...v];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(x=>({...this.target==="draft-7"?{type:"string"}:{},pattern:x.source}))])}break}case"number":{let p=f,{minimum:h,maximum:g,format:y,multipleOf:v,exclusiveMaximum:_,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof h=="number"&&(p.minimum=h,typeof b=="number"&&(b>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=f;p.type="object",p.properties={};let h=o.shape;for(let v in h)p.properties[v]=this.process(h[v],{...l,path:[...l.path,"properties",v]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(v=>{let _=o.shape[v]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=f;p.anyOf=o.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=f,h=this.process(o.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(o.right,{...l,path:[...l.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,v=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{let p=f;p.type="array";let h=o.items.map((v,_)=>this.process(v,{...l,path:[...l.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let v=this.process(o.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}o.rest&&(p.items=this.process(o.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=f;p.type="object",p.propertyNames=this.process(o.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=f,h=Pi(o.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=f,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),v?v.length===1?(h.contentMediaType=v[0],Object.assign(p,h)):p.anyOf=v.map(_=>({...h,contentMediaType:_})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,l);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"success":{let p=f;p.type="boolean";break}case"default":{this.process(o.innerType,l),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,l),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,l),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(o.innerType,l),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,l),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,l),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Je(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let y=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=y,{defId:y,ref:`${g("__shared")}#/${l}/${y}`}}if(d[1]===o)return{ref:"#"};let f=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:f}=s(d);l.def={...l.schema},f&&(l.defId=f);let p=l.schema;for(let h in p)delete p[h];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
183
-
184
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),f=m.def??m.schema,p={...f};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}m.isParent||this.override({zodSchema:d,jsonSchema:f,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var kS=S(()=>{});var _t=S(()=>{ds();Vp();Lp();dS();zc();Xp();Ir();jc();Bc();Um();Yp();xS();bS();SS();kS()});var Cf=S(()=>{_t()});function Of(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new sN(r)}var oN,sN,wS=S(()=>{_t();_t();Cf();oN=T("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>Up(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>bo(t,r,n),t.parseAsync=async(r,n)=>Zp(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>xo(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>jt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),sN=T("ZodMiniObject",(t,e)=>{Hc.init(t,e),oN.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var ES=S(()=>{});var $S=S(()=>{});var TS=S(()=>{});var PS=S(()=>{_t();Cf();wS();ES();_t();Bc();$S();TS()});var RS=S(()=>{PS()});var If=S(()=>{RS()});function Jt(t){return!!t._zod}function wo(t){let e=Object.values(t);if(e.length===0)return Of({});let r=e.every(Jt),n=e.every(o=>!Jt(o));if(r)return Of(t);if(n)return $p(t);throw new Error("Mixed Zod versions detected in object shape.")}function wn(t,e){return Jt(t)?bo(t,e):t.safeParse(e)}async function Xc(t,e){return Jt(t)?await xo(t,e):await t.safeParseAsync(e)}function En(t){if(!t)return;let e;if(Jt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function hs(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return wo(t)}}if(Jt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Qc(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function OS(t){return t.description}function IS(t){if(Jt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function eu(t){if(Jt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Li=S(()=>{$i();If()});var Af=S(()=>{_t()});var Fi={};Le(Fi,{ZodISODate:()=>NS,ZodISODateTime:()=>AS,ZodISODuration:()=>MS,ZodISOTime:()=>DS,date:()=>Df,datetime:()=>Nf,duration:()=>jf,time:()=>Mf});function Nf(t){return hS(AS,t)}function Df(t){return gS(NS,t)}function Mf(t){return yS(DS,t)}function jf(t){return _S(MS,t)}var AS,NS,DS,MS,zf=S(()=>{_t();Lf();AS=T("ZodISODateTime",(t,e)=>{iS.init(t,e),Ne.init(t,e)});NS=T("ZodISODate",(t,e)=>{aS.init(t,e),Ne.init(t,e)});DS=T("ZodISOTime",(t,e)=>{cS.init(t,e),Ne.init(t,e)});MS=T("ZodISODuration",(t,e)=>{uS.init(t,e),Ne.init(t,e)})});var jS,GV,Ui,Ff=S(()=>{_t();_t();jS=(t,e)=>{Dc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>zp(t,r)},flatten:{value:r=>jp(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},GV=T("ZodError",jS),Ui=T("ZodError",jS,{Parent:Error})});var zS,LS,FS,US,Uf=S(()=>{_t();Ff();zS=Fp(Ui),LS=Hp(Ui),FS=Bp(Ui),US=qp(Ui)});function $(t){return Hm(hN,t)}function ge(t){return df(VS,t)}function ZS(t){return pf(AN,t)}function et(t){return mf(NN,t)}function WS(t){return ff(DN,t)}function De(){return hf(MN)}function zN(t){return gf(jN,t)}function le(t,e){return vS(LN,t,e)}function z(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new GS(r)}function vt(t,e){return new GS({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ue.normalizeParams(e)})}function Pe(t,e){return new KS({type:"union",options:t,...ue.normalizeParams(e)})}function Bf(t,e,r){return new FN({type:"union",options:e,discriminator:t,...ue.normalizeParams(r)})}function ru(t,e){return new UN({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new HN({type:"record",keyType:t,valueType:e,...ue.normalizeParams(r)})}function Ct(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Hf({type:"enum",entries:r,...ue.normalizeParams(e)})}function q(t,e){return new ZN({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function JS(t){return new BN({type:"transform",transform:t})}function Me(t){return new YS({type:"optional",innerType:t})}function BS(t){return new qN({type:"nullable",innerType:t})}function WN(t,e){return new VN({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function KN(t,e){return new GN({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function JN(t,e){return new XS({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function XN(t,e){return new YN({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Zf(t,e){return new QN({type:"pipe",in:t,out:e})}function t1(t){return new e1({type:"readonly",innerType:t})}function r1(t){let e=new nt({check:"custom"});return e._zod.check=t,e}function ek(t,e){return Tf(QS,t??(()=>!0),e)}function n1(t,e={}){return Pf(QS,t,e)}function o1(t){let e=r1(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ue.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ue.issue(o))}},t(r.value,r)));return e}function qf(t,e){return Zf(JS(t),e)}var He,qS,hN,Ne,gN,HS,tu,yN,_N,vN,bN,xN,SN,kN,wN,EN,$N,TN,PN,RN,CN,ON,IN,VS,AN,NN,DN,MN,jN,LN,GS,KS,FN,UN,HN,Hf,ZN,BN,YS,qN,VN,GN,XS,YN,QN,e1,QS,Lf=S(()=>{_t();_t();Af();zf();Uf();He=T("ZodType",(t,e)=>(ve.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>jt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>zS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>FS(t,r,n),t.parseAsync=async(r,n)=>LS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>US(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(n1(r,n)),t.superRefine=r=>t.check(o1(r)),t.overwrite=r=>t.check(So(r)),t.optional=()=>Me(t),t.nullable=()=>BS(t),t.nullish=()=>Me(BS(t)),t.nonoptional=r=>JN(t,r),t.array=()=>le(t),t.or=r=>Pe([t,r]),t.and=r=>ru(t,r),t.transform=r=>Zf(t,JS(r)),t.default=r=>WN(t,r),t.prefault=r=>KN(t,r),t.catch=r=>XN(t,r),t.pipe=r=>Zf(t,r),t.readonly=()=>t1(t),t.describe=r=>{let n=t.clone();return kn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return kn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return kn.get(t);let n=t.clone();return kn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),qS=T("_ZodString",(t,e)=>{Di.init(t,e),He.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(yf(...n)),t.includes=(...n)=>t.check(bf(...n)),t.startsWith=(...n)=>t.check(xf(...n)),t.endsWith=(...n)=>t.check(Sf(...n)),t.min=(...n)=>t.check(fs(...n)),t.max=(...n)=>t.check(Kc(...n)),t.length=(...n)=>t.check(Jc(...n)),t.nonempty=(...n)=>t.check(fs(1,...n)),t.lowercase=n=>t.check(_f(n)),t.uppercase=n=>t.check(vf(n)),t.trim=()=>t.check(wf()),t.normalize=(...n)=>t.check(kf(...n)),t.toLowerCase=()=>t.check(Ef()),t.toUpperCase=()=>t.check($f())}),hN=T("ZodString",(t,e)=>{Di.init(t,e),qS.init(t,e),t.email=r=>t.check(Zm(gN,r)),t.url=r=>t.check(Gm(yN,r)),t.jwt=r=>t.check(lf(IN,r)),t.emoji=r=>t.check(Km(_N,r)),t.guid=r=>t.check(qc(HS,r)),t.uuid=r=>t.check(Bm(tu,r)),t.uuidv4=r=>t.check(qm(tu,r)),t.uuidv6=r=>t.check(Vm(tu,r)),t.uuidv7=r=>t.check(Wm(tu,r)),t.nanoid=r=>t.check(Jm(vN,r)),t.guid=r=>t.check(qc(HS,r)),t.cuid=r=>t.check(Ym(bN,r)),t.cuid2=r=>t.check(Xm(xN,r)),t.ulid=r=>t.check(Qm(SN,r)),t.base64=r=>t.check(af(RN,r)),t.base64url=r=>t.check(cf(CN,r)),t.xid=r=>t.check(ef(kN,r)),t.ksuid=r=>t.check(tf(wN,r)),t.ipv4=r=>t.check(rf(EN,r)),t.ipv6=r=>t.check(nf($N,r)),t.cidrv4=r=>t.check(of(TN,r)),t.cidrv6=r=>t.check(sf(PN,r)),t.e164=r=>t.check(uf(ON,r)),t.datetime=r=>t.check(Nf(r)),t.date=r=>t.check(Df(r)),t.time=r=>t.check(Mf(r)),t.duration=r=>t.check(jf(r))});Ne=T("ZodStringFormat",(t,e)=>{we.init(t,e),qS.init(t,e)}),gN=T("ZodEmail",(t,e)=>{rm.init(t,e),Ne.init(t,e)}),HS=T("ZodGUID",(t,e)=>{em.init(t,e),Ne.init(t,e)}),tu=T("ZodUUID",(t,e)=>{tm.init(t,e),Ne.init(t,e)}),yN=T("ZodURL",(t,e)=>{nm.init(t,e),Ne.init(t,e)}),_N=T("ZodEmoji",(t,e)=>{om.init(t,e),Ne.init(t,e)}),vN=T("ZodNanoID",(t,e)=>{sm.init(t,e),Ne.init(t,e)}),bN=T("ZodCUID",(t,e)=>{im.init(t,e),Ne.init(t,e)}),xN=T("ZodCUID2",(t,e)=>{am.init(t,e),Ne.init(t,e)}),SN=T("ZodULID",(t,e)=>{cm.init(t,e),Ne.init(t,e)}),kN=T("ZodXID",(t,e)=>{um.init(t,e),Ne.init(t,e)}),wN=T("ZodKSUID",(t,e)=>{lm.init(t,e),Ne.init(t,e)}),EN=T("ZodIPv4",(t,e)=>{dm.init(t,e),Ne.init(t,e)}),$N=T("ZodIPv6",(t,e)=>{pm.init(t,e),Ne.init(t,e)}),TN=T("ZodCIDRv4",(t,e)=>{mm.init(t,e),Ne.init(t,e)}),PN=T("ZodCIDRv6",(t,e)=>{fm.init(t,e),Ne.init(t,e)}),RN=T("ZodBase64",(t,e)=>{hm.init(t,e),Ne.init(t,e)}),CN=T("ZodBase64URL",(t,e)=>{gm.init(t,e),Ne.init(t,e)}),ON=T("ZodE164",(t,e)=>{ym.init(t,e),Ne.init(t,e)}),IN=T("ZodJWT",(t,e)=>{_m.init(t,e),Ne.init(t,e)}),VS=T("ZodNumber",(t,e)=>{Uc.init(t,e),He.init(t,e),t.gt=(n,o)=>t.check(Wc(n,o)),t.gte=(n,o)=>t.check(zi(n,o)),t.min=(n,o)=>t.check(zi(n,o)),t.lt=(n,o)=>t.check(Vc(n,o)),t.lte=(n,o)=>t.check(ji(n,o)),t.max=(n,o)=>t.check(ji(n,o)),t.int=n=>t.check(ZS(n)),t.safe=n=>t.check(ZS(n)),t.positive=n=>t.check(Wc(0,n)),t.nonnegative=n=>t.check(zi(0,n)),t.negative=n=>t.check(Vc(0,n)),t.nonpositive=n=>t.check(ji(0,n)),t.multipleOf=(n,o)=>t.check(Gc(n,o)),t.step=(n,o)=>t.check(Gc(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});AN=T("ZodNumberFormat",(t,e)=>{vm.init(t,e),VS.init(t,e)});NN=T("ZodBoolean",(t,e)=>{bm.init(t,e),He.init(t,e)});DN=T("ZodNull",(t,e)=>{xm.init(t,e),He.init(t,e)});MN=T("ZodUnknown",(t,e)=>{Sm.init(t,e),He.init(t,e)});jN=T("ZodNever",(t,e)=>{km.init(t,e),He.init(t,e)});LN=T("ZodArray",(t,e)=>{wm.init(t,e),He.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(fs(r,n)),t.nonempty=r=>t.check(fs(1,r)),t.max=(r,n)=>t.check(Kc(r,n)),t.length=(r,n)=>t.check(Jc(r,n)),t.unwrap=()=>t.element});GS=T("ZodObject",(t,e)=>{Hc.init(t,e),He.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ct(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:De()}),t.loose=()=>t.clone({...t._zod.def,catchall:De()}),t.strict=()=>t.clone({...t._zod.def,catchall:zN()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ue.extend(t,r),t.merge=r=>ue.merge(t,r),t.pick=r=>ue.pick(t,r),t.omit=r=>ue.omit(t,r),t.partial=(...r)=>ue.partial(YS,t,r[0]),t.required=(...r)=>ue.required(XS,t,r[0])});KS=T("ZodUnion",(t,e)=>{Zc.init(t,e),He.init(t,e),t.options=e.options});FN=T("ZodDiscriminatedUnion",(t,e)=>{KS.init(t,e),Em.init(t,e)});UN=T("ZodIntersection",(t,e)=>{$m.init(t,e),He.init(t,e)});HN=T("ZodRecord",(t,e)=>{Tm.init(t,e),He.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Hf=T("ZodEnum",(t,e)=>{Pm.init(t,e),He.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Hf({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Hf({...e,checks:[],...ue.normalizeParams(o),entries:s})}});ZN=T("ZodLiteral",(t,e)=>{Rm.init(t,e),He.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});BN=T("ZodTransform",(t,e)=>{Cm.init(t,e),He.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ue.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ue.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});YS=T("ZodOptional",(t,e)=>{Om.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});qN=T("ZodNullable",(t,e)=>{Im.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});VN=T("ZodDefault",(t,e)=>{Am.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});GN=T("ZodPrefault",(t,e)=>{Nm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});XS=T("ZodNonOptional",(t,e)=>{Dm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});YN=T("ZodCatch",(t,e)=>{Mm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});QN=T("ZodPipe",(t,e)=>{jm.init(t,e),He.init(t,e),t.in=e.in,t.out=e.out});e1=T("ZodReadonly",(t,e)=>{zm.init(t,e),He.init(t,e)});QS=T("ZodCustom",(t,e)=>{Lm.init(t,e),He.init(t,e)})});var tk=S(()=>{});var rk=S(()=>{});var nk=S(()=>{_t();Lf();Af();Ff();Uf();tk();_t();mS();Bc();zf();rk();Mt(pS())});var ok=S(()=>{nk()});var sk=S(()=>{ok()});function Sk(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function kk(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Wf,ik,$n,ou,Ye,ak,ck,l3,a1,c1,Gf,zt,Hi,uk,ot,Yt,Xt,st,su,lk,Kf,dk,pk,Jf,Zi,W,Yf,mk,fk,d3,iu,u1,au,l1,Bi,gs,hk,d1,p1,m1,f1,h1,g1,Xf,y1,_1,Qf,cu,v1,b1,uu,x1,qi,Vi,S1,Wi,ys,k1,Gi,lu,du,pu,p3,mu,fu,hu,gk,yk,_k,eh,vk,Ki,_s,bk,w1,vs,E1,bs,$1,th,T1,gu,P1,R1,C1,O1,I1,A1,N1,D1,M1,j1,xs,z1,L1,yu,rh,nh,oh,F1,U1,H1,sh,Z1,B1,q1,V1,W1,xk,Ss,G1,_u,m3,K1,ks,J1,f3,Ji,Y1,ih,X1,Q1,eD,tD,rD,nD,oD,nu,sD,iD,aD,Yi,ah,cD,uD,lD,dD,pD,mD,fD,hD,gD,yD,_D,vD,bD,xD,SD,kD,wD,ED,ws,$D,TD,PD,vu,RD,CD,OD,ch,ID,h3,g3,y3,_3,v3,b3,Z,Vf,Eo=S(()=>{sk();Wf="2025-11-25",ik=[Wf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],$n="io.modelcontextprotocol/related-task",ou="2.0",Ye=ek(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ak=Pe([$(),ge().int()]),ck=$(),l3=vt({ttl:ge().optional(),pollInterval:ge().optional()}),a1=z({ttl:ge().optional()}),c1=z({taskId:$()}),Gf=vt({progressToken:ak.optional(),[$n]:c1.optional()}),zt=z({_meta:Gf.optional()}),Hi=zt.extend({task:a1.optional()}),uk=t=>Hi.safeParse(t).success,ot=z({method:$(),params:zt.loose().optional()}),Yt=z({_meta:Gf.optional()}),Xt=z({method:$(),params:Yt.loose().optional()}),st=vt({_meta:Gf.optional()}),su=Pe([$(),ge().int()]),lk=z({jsonrpc:q(ou),id:su,...ot.shape}).strict(),Kf=t=>lk.safeParse(t).success,dk=z({jsonrpc:q(ou),...Xt.shape}).strict(),pk=t=>dk.safeParse(t).success,Jf=z({jsonrpc:q(ou),id:su,result:st}).strict(),Zi=t=>Jf.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(W||(W={}));Yf=z({jsonrpc:q(ou),id:su.optional(),error:z({code:ge().int(),message:$(),data:De().optional()})}).strict(),mk=t=>Yf.safeParse(t).success,fk=Pe([lk,dk,Jf,Yf]),d3=Pe([Jf,Yf]),iu=st.strict(),u1=Yt.extend({requestId:su.optional(),reason:$().optional()}),au=Xt.extend({method:q("notifications/cancelled"),params:u1}),l1=z({src:$(),mimeType:$().optional(),sizes:le($()).optional(),theme:Ct(["light","dark"]).optional()}),Bi=z({icons:le(l1).optional()}),gs=z({name:$(),title:$().optional()}),hk=gs.extend({...gs.shape,...Bi.shape,version:$(),websiteUrl:$().optional(),description:$().optional()}),d1=ru(z({applyDefaults:et().optional()}),Ee($(),De())),p1=qf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ru(z({form:d1.optional(),url:Ye.optional()}),Ee($(),De()).optional())),m1=vt({list:Ye.optional(),cancel:Ye.optional(),requests:vt({sampling:vt({createMessage:Ye.optional()}).optional(),elicitation:vt({create:Ye.optional()}).optional()}).optional()}),f1=vt({list:Ye.optional(),cancel:Ye.optional(),requests:vt({tools:vt({call:Ye.optional()}).optional()}).optional()}),h1=z({experimental:Ee($(),Ye).optional(),sampling:z({context:Ye.optional(),tools:Ye.optional()}).optional(),elicitation:p1.optional(),roots:z({listChanged:et().optional()}).optional(),tasks:m1.optional(),extensions:Ee($(),Ye).optional()}),g1=zt.extend({protocolVersion:$(),capabilities:h1,clientInfo:hk}),Xf=ot.extend({method:q("initialize"),params:g1}),y1=z({experimental:Ee($(),Ye).optional(),logging:Ye.optional(),completions:Ye.optional(),prompts:z({listChanged:et().optional()}).optional(),resources:z({subscribe:et().optional(),listChanged:et().optional()}).optional(),tools:z({listChanged:et().optional()}).optional(),tasks:f1.optional(),extensions:Ee($(),Ye).optional()}),_1=st.extend({protocolVersion:$(),capabilities:y1,serverInfo:hk,instructions:$().optional()}),Qf=Xt.extend({method:q("notifications/initialized"),params:Yt.optional()}),cu=ot.extend({method:q("ping"),params:zt.optional()}),v1=z({progress:ge(),total:Me(ge()),message:Me($())}),b1=z({...Yt.shape,...v1.shape,progressToken:ak}),uu=Xt.extend({method:q("notifications/progress"),params:b1}),x1=zt.extend({cursor:ck.optional()}),qi=ot.extend({params:x1.optional()}),Vi=st.extend({nextCursor:ck.optional()}),S1=Ct(["working","input_required","completed","failed","cancelled"]),Wi=z({taskId:$(),status:S1,ttl:Pe([ge(),WS()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:Me(ge()),statusMessage:Me($())}),ys=st.extend({task:Wi}),k1=Yt.merge(Wi),Gi=Xt.extend({method:q("notifications/tasks/status"),params:k1}),lu=ot.extend({method:q("tasks/get"),params:zt.extend({taskId:$()})}),du=st.merge(Wi),pu=ot.extend({method:q("tasks/result"),params:zt.extend({taskId:$()})}),p3=st.loose(),mu=qi.extend({method:q("tasks/list")}),fu=Vi.extend({tasks:le(Wi)}),hu=ot.extend({method:q("tasks/cancel"),params:zt.extend({taskId:$()})}),gk=st.merge(Wi),yk=z({uri:$(),mimeType:Me($()),_meta:Ee($(),De()).optional()}),_k=yk.extend({text:$()}),eh=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),vk=yk.extend({blob:eh}),Ki=Ct(["user","assistant"]),_s=z({audience:le(Ki).optional(),priority:ge().min(0).max(1).optional(),lastModified:Fi.datetime({offset:!0}).optional()}),bk=z({...gs.shape,...Bi.shape,uri:$(),description:Me($()),mimeType:Me($()),size:Me(ge()),annotations:_s.optional(),_meta:Me(vt({}))}),w1=z({...gs.shape,...Bi.shape,uriTemplate:$(),description:Me($()),mimeType:Me($()),annotations:_s.optional(),_meta:Me(vt({}))}),vs=qi.extend({method:q("resources/list")}),E1=Vi.extend({resources:le(bk)}),bs=qi.extend({method:q("resources/templates/list")}),$1=Vi.extend({resourceTemplates:le(w1)}),th=zt.extend({uri:$()}),T1=th,gu=ot.extend({method:q("resources/read"),params:T1}),P1=st.extend({contents:le(Pe([_k,vk]))}),R1=Xt.extend({method:q("notifications/resources/list_changed"),params:Yt.optional()}),C1=th,O1=ot.extend({method:q("resources/subscribe"),params:C1}),I1=th,A1=ot.extend({method:q("resources/unsubscribe"),params:I1}),N1=Yt.extend({uri:$()}),D1=Xt.extend({method:q("notifications/resources/updated"),params:N1}),M1=z({name:$(),description:Me($()),required:Me(et())}),j1=z({...gs.shape,...Bi.shape,description:Me($()),arguments:Me(le(M1)),_meta:Me(vt({}))}),xs=qi.extend({method:q("prompts/list")}),z1=Vi.extend({prompts:le(j1)}),L1=zt.extend({name:$(),arguments:Ee($(),$()).optional()}),yu=ot.extend({method:q("prompts/get"),params:L1}),rh=z({type:q("text"),text:$(),annotations:_s.optional(),_meta:Ee($(),De()).optional()}),nh=z({type:q("image"),data:eh,mimeType:$(),annotations:_s.optional(),_meta:Ee($(),De()).optional()}),oh=z({type:q("audio"),data:eh,mimeType:$(),annotations:_s.optional(),_meta:Ee($(),De()).optional()}),F1=z({type:q("tool_use"),name:$(),id:$(),input:Ee($(),De()),_meta:Ee($(),De()).optional()}),U1=z({type:q("resource"),resource:Pe([_k,vk]),annotations:_s.optional(),_meta:Ee($(),De()).optional()}),H1=bk.extend({type:q("resource_link")}),sh=Pe([rh,nh,oh,H1,U1]),Z1=z({role:Ki,content:sh}),B1=st.extend({description:$().optional(),messages:le(Z1)}),q1=Xt.extend({method:q("notifications/prompts/list_changed"),params:Yt.optional()}),V1=z({title:$().optional(),readOnlyHint:et().optional(),destructiveHint:et().optional(),idempotentHint:et().optional(),openWorldHint:et().optional()}),W1=z({taskSupport:Ct(["required","optional","forbidden"]).optional()}),xk=z({...gs.shape,...Bi.shape,description:$().optional(),inputSchema:z({type:q("object"),properties:Ee($(),Ye).optional(),required:le($()).optional()}).catchall(De()),outputSchema:z({type:q("object"),properties:Ee($(),Ye).optional(),required:le($()).optional()}).catchall(De()).optional(),annotations:V1.optional(),execution:W1.optional(),_meta:Ee($(),De()).optional()}),Ss=qi.extend({method:q("tools/list")}),G1=Vi.extend({tools:le(xk)}),_u=st.extend({content:le(sh).default([]),structuredContent:Ee($(),De()).optional(),isError:et().optional()}),m3=_u.or(st.extend({toolResult:De()})),K1=Hi.extend({name:$(),arguments:Ee($(),De()).optional()}),ks=ot.extend({method:q("tools/call"),params:K1}),J1=Xt.extend({method:q("notifications/tools/list_changed"),params:Yt.optional()}),f3=z({autoRefresh:et().default(!0),debounceMs:ge().int().nonnegative().default(300)}),Ji=Ct(["debug","info","notice","warning","error","critical","alert","emergency"]),Y1=zt.extend({level:Ji}),ih=ot.extend({method:q("logging/setLevel"),params:Y1}),X1=Yt.extend({level:Ji,logger:$().optional(),data:De()}),Q1=Xt.extend({method:q("notifications/message"),params:X1}),eD=z({name:$().optional()}),tD=z({hints:le(eD).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),rD=z({mode:Ct(["auto","required","none"]).optional()}),nD=z({type:q("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:le(sh).default([]),structuredContent:z({}).loose().optional(),isError:et().optional(),_meta:Ee($(),De()).optional()}),oD=Bf("type",[rh,nh,oh]),nu=Bf("type",[rh,nh,oh,F1,nD]),sD=z({role:Ki,content:Pe([nu,le(nu)]),_meta:Ee($(),De()).optional()}),iD=Hi.extend({messages:le(sD),modelPreferences:tD.optional(),systemPrompt:$().optional(),includeContext:Ct(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:le($()).optional(),metadata:Ye.optional(),tools:le(xk).optional(),toolChoice:rD.optional()}),aD=ot.extend({method:q("sampling/createMessage"),params:iD}),Yi=st.extend({model:$(),stopReason:Me(Ct(["endTurn","stopSequence","maxTokens"]).or($())),role:Ki,content:oD}),ah=st.extend({model:$(),stopReason:Me(Ct(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:Ki,content:Pe([nu,le(nu)])}),cD=z({type:q("boolean"),title:$().optional(),description:$().optional(),default:et().optional()}),uD=z({type:q("string"),title:$().optional(),description:$().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:Ct(["email","uri","date","date-time"]).optional(),default:$().optional()}),lD=z({type:Ct(["number","integer"]),title:$().optional(),description:$().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),dD=z({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),default:$().optional()}),pD=z({type:q("string"),title:$().optional(),description:$().optional(),oneOf:le(z({const:$(),title:$()})),default:$().optional()}),mD=z({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),enumNames:le($()).optional(),default:$().optional()}),fD=Pe([dD,pD]),hD=z({type:q("array"),title:$().optional(),description:$().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({type:q("string"),enum:le($())}),default:le($()).optional()}),gD=z({type:q("array"),title:$().optional(),description:$().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({anyOf:le(z({const:$(),title:$()}))}),default:le($()).optional()}),yD=Pe([hD,gD]),_D=Pe([mD,fD,yD]),vD=Pe([_D,cD,uD,lD]),bD=Hi.extend({mode:q("form").optional(),message:$(),requestedSchema:z({type:q("object"),properties:Ee($(),vD),required:le($()).optional()})}),xD=Hi.extend({mode:q("url"),message:$(),elicitationId:$(),url:$().url()}),SD=Pe([bD,xD]),kD=ot.extend({method:q("elicitation/create"),params:SD}),wD=Yt.extend({elicitationId:$()}),ED=Xt.extend({method:q("notifications/elicitation/complete"),params:wD}),ws=st.extend({action:Ct(["accept","decline","cancel"]),content:qf(t=>t===null?void 0:t,Ee($(),Pe([$(),ge(),et(),le($())])).optional())}),$D=z({type:q("ref/resource"),uri:$()}),TD=z({type:q("ref/prompt"),name:$()}),PD=zt.extend({ref:Pe([TD,$D]),argument:z({name:$(),value:$()}),context:z({arguments:Ee($(),$()).optional()}).optional()}),vu=ot.extend({method:q("completion/complete"),params:PD});RD=st.extend({completion:vt({values:le($()).max(100),total:Me(ge().int()),hasMore:Me(et())})}),CD=z({uri:$().startsWith("file://"),name:$().optional(),_meta:Ee($(),De()).optional()}),OD=ot.extend({method:q("roots/list"),params:zt.optional()}),ch=st.extend({roots:le(CD)}),ID=Xt.extend({method:q("notifications/roots/list_changed"),params:Yt.optional()}),h3=Pe([cu,Xf,vu,ih,yu,xs,vs,bs,gu,O1,A1,ks,Ss,lu,pu,mu,hu]),g3=Pe([au,uu,Qf,ID,Gi]),y3=Pe([iu,Yi,ah,ws,ch,du,fu,ys]),_3=Pe([cu,aD,kD,OD,lu,pu,mu,hu]),v3=Pe([au,uu,Q1,D1,R1,J1,q1,Gi,ED]),b3=Pe([iu,_1,RD,B1,z1,E1,$1,P1,_u,G1,du,fu,ys]),Z=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===W.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Vf(o.elicitations,r)}return new t(e,r,n)}},Vf=class extends Z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Tn(t){return t==="completed"||t==="failed"||t==="cancelled"}var wk=S(()=>{});var $k,Ek,Tk,bu=S(()=>{$k=Symbol("Let zodToJsonSchema decide on which parser to use"),Ek={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Tk=t=>typeof t=="string"?{...Ek,name:t}:{...Ek,...t}});var Pk,uh=S(()=>{bu();Pk=t=>{let e=Tk(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function lh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,o){t[e]=r,lh(t,e,n,o)}var Pn=S(()=>{});var xu,Su=S(()=>{xu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?xu(e,t.currentPath):e.join("/")}}var Qt=S(()=>{Su()});function Rk(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==I.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var dh=S(()=>{$i();Pn();We()});function Ck(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var ph=S(()=>{Pn()});function Ok(){return{type:"boolean"}}var mh=S(()=>{});function ku(t,e){return Y(t.type._def,e)}var wu=S(()=>{We()});var Ik,fh=S(()=>{We();Ik=(t,e)=>Y(t.innerType._def,e)});function hh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>hh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return AD(t,e)}}var AD,gh=S(()=>{Pn();AD=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function Ak(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var yh=S(()=>{We()});function Nk(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):je(e)}var _h=S(()=>{We();Qt()});function Dk(t){return{type:"string",enum:Array.from(t.values)}}var vh=S(()=>{});function Mk(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(ND(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var ND,bh=S(()=>{We();ND=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function jk(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var xh=S(()=>{});function Eu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":hr(r,"email",n.message,e);break;case"format:idn-email":hr(r,"idn-email",n.message,e);break;case"pattern:zod":bt(r,fr.email,n.message,e);break}break;case"url":hr(r,"uri",n.message,e);break;case"uuid":hr(r,"uuid",n.message,e);break;case"regex":bt(r,n.regex,n.message,e);break;case"cuid":bt(r,fr.cuid,n.message,e);break;case"cuid2":bt(r,fr.cuid2,n.message,e);break;case"startsWith":bt(r,RegExp(`^${kh(n.value,e)}`),n.message,e);break;case"endsWith":bt(r,RegExp(`${kh(n.value,e)}$`),n.message,e);break;case"datetime":hr(r,"date-time",n.message,e);break;case"date":hr(r,"date",n.message,e);break;case"time":hr(r,"time",n.message,e);break;case"duration":hr(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{bt(r,RegExp(kh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&hr(r,"ipv4",n.message,e),n.version!=="v4"&&hr(r,"ipv6",n.message,e);break}case"base64url":bt(r,fr.base64url,n.message,e);break;case"jwt":bt(r,fr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&bt(r,fr.ipv4Cidr,n.message,e),n.version!=="v4"&&bt(r,fr.ipv6Cidr,n.message,e);break}case"emoji":bt(r,fr.emoji(),n.message,e);break;case"ulid":{bt(r,fr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{hr(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{bt(r,fr.base64,n.message,e);break}}break}case"nanoid":bt(r,fr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function kh(t,e){return e.patternStrategy==="escape"?MD(t):t}function MD(t){let e="";for(let r=0;r<t.length;r++)DD.has(t[r])||(e+="\\"),e+=t[r];return e}function hr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):de(t,"format",e,r,n)}function bt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:zk(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",zk(e,n),r,n)}function zk(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
185
- ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
186
- ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
187
- `:`[${n[c]}\r
188
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Sh,fr,DD,$u=S(()=>{Pn();fr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Sh===void 0&&(Sh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sh),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};DD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Tu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===I.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===I.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Eu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===I.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===I.ZodBranded&&t.keyType._def.type._def.typeName===I.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ku(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Pu=S(()=>{$i();We();$u();wu();Qt()});function Lk(t,e){if(e.mapStrategy==="record")return Tu(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var wh=S(()=>{We();Pu();Qt()});function Fk(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Eh=S(()=>{});function Uk(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var $h=S(()=>{Qt()});function Hk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Th=S(()=>{});function Bk(t,e){if(e.target==="openApi3")return Zk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Xi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Xi[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Zk(t,e)}var Xi,Zk,Ru=S(()=>{We();Xi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Zk=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function qk(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Xi[t.innerType._def.typeName],nullable:!0}:{type:[Xi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Ph=S(()=>{We();Ru()});function Vk(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",lh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var Rh=S(()=>{Pn()});function Wk(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=zD(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=Y(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||o.push(a))}o.length&&(n.required=o);let i=jD(t,e);return i!==void 0&&(n.additionalProperties=i),n}function jD(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function zD(t){try{return t.isOptional()}catch{return!0}}var Ch=S(()=>{We()});var Gk,Oh=S(()=>{We();Qt();Gk=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:je(e)},r]}:je(e)}});var Kk,Ih=S(()=>{We();Kk=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let r=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Jk(t,e){return Y(t.type._def,e)}var Ah=S(()=>{We()});function Yk(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Nh=S(()=>{Pn();We()});function Xk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Dh=S(()=>{We()});function Qk(t){return{not:je(t)}}var Mh=S(()=>{Qt()});function e0(t){return je(t)}var jh=S(()=>{Qt()});var t0,zh=S(()=>{We();t0=(t,e)=>Y(t.innerType._def,e)});var r0,Lh=S(()=>{$i();Qt();dh();ph();mh();wu();fh();gh();yh();_h();vh();bh();xh();wh();Eh();$h();Th();Ph();Rh();Ch();Oh();Ih();Ah();Pu();Nh();$u();Dh();Mh();Ru();jh();zh();r0=(t,e,r)=>{switch(e){case I.ZodString:return Eu(t,r);case I.ZodNumber:return Vk(t,r);case I.ZodObject:return Wk(t,r);case I.ZodBigInt:return Ck(t,r);case I.ZodBoolean:return Ok();case I.ZodDate:return hh(t,r);case I.ZodUndefined:return Qk(r);case I.ZodNull:return Hk(r);case I.ZodArray:return Rk(t,r);case I.ZodUnion:case I.ZodDiscriminatedUnion:return Bk(t,r);case I.ZodIntersection:return Mk(t,r);case I.ZodTuple:return Xk(t,r);case I.ZodRecord:return Tu(t,r);case I.ZodLiteral:return jk(t,r);case I.ZodEnum:return Dk(t);case I.ZodNativeEnum:return Fk(t);case I.ZodNullable:return qk(t,r);case I.ZodOptional:return Gk(t,r);case I.ZodMap:return Lk(t,r);case I.ZodSet:return Yk(t,r);case I.ZodLazy:return()=>t.getter()._def;case I.ZodPromise:return Jk(t,r);case I.ZodNaN:case I.ZodNever:return Uk(r);case I.ZodEffects:return Nk(t,r);case I.ZodAny:return je(r);case I.ZodUnknown:return e0(r);case I.ZodDefault:return Ak(t,r);case I.ZodBranded:return ku(t,r);case I.ZodReadonly:return t0(t,r);case I.ZodCatch:return Ik(t,r);case I.ZodPipeline:return Kk(t,r);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(n=>{})(e)}}});function Y(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==$k)return a}if(n&&!r){let a=LD(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=r0(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&FD(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var LD,FD,We=S(()=>{bu();Lh();Su();Qt();LD=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:xu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},FD=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var n0=S(()=>{});var Fh,Uh=S(()=>{We();uh();Qt();Fh=(t,e)=>{let r=Pk(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:Y(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??je(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??je(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var o0=S(()=>{bu();uh();Pn();Su();We();n0();Qt();dh();ph();mh();wu();fh();gh();yh();_h();vh();bh();xh();wh();Eh();$h();Th();Ph();Rh();Ch();Oh();Ih();Ah();zh();Pu();Nh();$u();Dh();Mh();Ru();jh();Lh();Uh();Uh()});function UD(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Hh(t,e){return Jt(t)?Rf(t,{target:UD(e?.target),io:e?.pipeStrategy??"input"}):Fh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Zh(t){let r=En(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=eu(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bh(t,e){let r=wn(t,e);if(!r.success)throw r.error;return r.data}var qh=S(()=>{If();Li();o0()});function s0(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function i0(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];s0(i)&&s0(s)?r[o]={...i,...s}:r[o]=s}return r}var HD,Cu,a0=S(()=>{Li();Eo();wk();qh();HD=6e4,Cu=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(au,r=>{this._oncancel(r)}),this.setNotificationHandler(uu,r=>{this._onprogress(r)}),this.setRequestHandler(cu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(lu,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(W.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(pu,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,m=new Z(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new Z(W.InvalidParams,`Task not found: ${s}`);if(!Tn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Tn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[$n]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(mu,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Z(W.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(hu,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Tn(o.status))throw new Z(W.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Z(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(W.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Zi(s)||mk(s)?this._onresponse(s):Kf(s)?this._onrequest(s,i):pk(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[$n]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:W.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=uk(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,m)=>{if(i.signal.aborted)throw new Z(W.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let p=f.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:W.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Zi(e))n(e);else{let i=new Z(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Zi(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Zi(e))o(e);else{let i=Z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(W.InternalError,String(i))}}return}let s;try{let i=await this.request(e,ys,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(W.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Tn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(W.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(W.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(W.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=v=>{d(v)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){l(v);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[$n]:c}});let p=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let _=v instanceof Z?v:new Z(W.RequestTimeout,String(v));d(_)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return d(v);try{let _=wn(r,v.result);_.success?u(_.data):d(_.error)}catch(_){d(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??HD,g=()=>p(Z.fromError(W.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let v=_=>{let b=this._responseHandlers.get(m);b?b(_):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(m),d(_)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(m),d(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},du,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},fu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},gk,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[$n]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[$n]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[$n]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Zh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Bh(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Zh(e);this._notificationHandlers.set(n,o=>{let s=Bh(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Kf(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Z(W.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Z(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new Z(W.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Gi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Tn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new Z(W.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Tn(a.status))throw new Z(W.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Gi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Tn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ta=M(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var Qi=class{};he._CodeOrName=Qi;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var $o=class extends Qi{constructor(e){if(super(),!he.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};he.Name=$o;var er=class extends Qi{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof $o&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=er;he.nil=new er("");function c0(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Wh(r,e[n]),r.push(t[++n]);return new er(r)}he._=c0;var Vh=new er("+");function u0(t,...e){let r=[ea(t[0])],n=0;for(;n<e.length;)r.push(Vh),Wh(r,e[n]),r.push(Vh,ea(t[++n]));return ZD(r),new er(r)}he.str=u0;function Wh(t,e){e instanceof er?t.push(...e._items):e instanceof $o?t.push(e):t.push(VD(e))}he.addCodeArg=Wh;function ZD(t){let e=1;for(;e<t.length-1;){if(t[e]===Vh){let r=BD(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function BD(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof $o||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof $o))return`"${t}${e.slice(1)}`}function qD(t,e){return e.emptyStr()?t:t.emptyStr()?e:u0`${t}${e}`}he.strConcat=qD;function VD(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ea(Array.isArray(t)?t.join(","):t)}function WD(t){return new er(ea(t))}he.stringify=WD;function ea(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=ea;function GD(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new er(`.${t}`):c0`[${t}]`}he.getProperty=GD;function KD(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new er(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=KD;function JD(t){return new er(t.toString())}he.regexpCode=JD});var Jh=M(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.ValueScope=It.ValueScopeName=It.Scope=It.varKinds=It.UsedValueState=void 0;var Ot=ta(),Gh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ou;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ou||(It.UsedValueState=Ou={}));It.varKinds={const:new Ot.Name("const"),let:new Ot.Name("let"),var:new Ot.Name("var")};var Iu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ot.Name?e:this.name(e)}name(e){return new Ot.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};It.Scope=Iu;var Au=class extends Ot.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ot._)`.${new Ot.Name(r)}[${n}]`}};It.ValueScopeName=Au;var YD=(0,Ot._)`\n`,Kh=class extends Iu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?YD:Ot.nil}}get(){return this._scope}name(e){return new Au(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ot._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ot.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Ou.Started);let d=r(u);if(d){let l=this.opts.es5?It.varKinds.var:It.varKinds.const;s=(0,Ot._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Ot._)`${s}${d}${this.opts._n}`;else throw new Gh(u);c.set(u,Ou.Completed)})}return s}};It.ValueScope=Kh});var ne=M(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.or=oe.and=oe.not=oe.CodeGen=oe.operators=oe.varKinds=oe.ValueScopeName=oe.ValueScope=oe.Scope=oe.Name=oe.regexpCode=oe.stringify=oe.getProperty=oe.nil=oe.strConcat=oe.str=oe._=void 0;var pe=ta(),gr=Jh(),Rn=ta();Object.defineProperty(oe,"_",{enumerable:!0,get:function(){return Rn._}});Object.defineProperty(oe,"str",{enumerable:!0,get:function(){return Rn.str}});Object.defineProperty(oe,"strConcat",{enumerable:!0,get:function(){return Rn.strConcat}});Object.defineProperty(oe,"nil",{enumerable:!0,get:function(){return Rn.nil}});Object.defineProperty(oe,"getProperty",{enumerable:!0,get:function(){return Rn.getProperty}});Object.defineProperty(oe,"stringify",{enumerable:!0,get:function(){return Rn.stringify}});Object.defineProperty(oe,"regexpCode",{enumerable:!0,get:function(){return Rn.regexpCode}});Object.defineProperty(oe,"Name",{enumerable:!0,get:function(){return Rn.Name}});var ju=Jh();Object.defineProperty(oe,"Scope",{enumerable:!0,get:function(){return ju.Scope}});Object.defineProperty(oe,"ValueScope",{enumerable:!0,get:function(){return ju.ValueScope}});Object.defineProperty(oe,"ValueScopeName",{enumerable:!0,get:function(){return ju.ValueScopeName}});Object.defineProperty(oe,"varKinds",{enumerable:!0,get:function(){return ju.varKinds}});oe.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var Jr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Yh=class extends Jr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?gr.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=$s(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},Nu=class extends Jr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=$s(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return Mu(e,this.rhs)}},Xh=class extends Nu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qh=class extends Jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},eg=class extends Jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},tg=class extends Jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},rg=class extends Jr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=$s(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},ra=class extends Jr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(XD(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ro(e,r.names),{})}},Yr=class extends ra{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},ng=class extends ra{},Es=class extends Yr{};Es.kind="else";var To=class t extends Yr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Es(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(l0(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=$s(this.condition,e,r),this}get names(){let e=super.names;return Mu(e,this.condition),this.else&&Ro(e,this.else.names),e}};To.kind="if";var Po=class extends Yr{};Po.kind="for";var og=class extends Po{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=$s(this.iteration,e,r),this}get names(){return Ro(super.names,this.iteration.names)}},sg=class extends Po{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?gr.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Mu(super.names,this.from);return Mu(e,this.to)}},Du=class extends Po{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=$s(this.iterable,e,r),this}get names(){return Ro(super.names,this.iterable.names)}},na=class extends Yr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};na.kind="func";var oa=class extends ra{render(e){return"return "+super.render(e)}};oa.kind="return";var ig=class extends Yr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Ro(e,this.catch.names),this.finally&&Ro(e,this.finally.names),e}},sa=class extends Yr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};sa.kind="catch";var ia=class extends Yr{render(e){return"finally"+super.render(e)}};ia.kind="finally";var ag=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
189
- `:""},this._extScope=e,this._scope=new gr.Scope({parent:e}),this._nodes=[new ng]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Yh(e,s,n)),s}const(e,r,n){return this._def(gr.varKinds.const,e,r,n)}let(e,r,n){return this._def(gr.varKinds.let,e,r,n)}var(e,r,n){return this._def(gr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Nu(e,r,n))}add(e,r){return this._leafNode(new Xh(e,oe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new rg(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,pe.addCodeArg)(r,o));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new To(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new To(e))}else(){return this._elseNode(new Es)}endIf(){return this._endBlockNode(To,Es)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new og(e),r)}forRange(e,r,n,o,s=this.opts.es5?gr.varKinds.var:gr.varKinds.let){let i=this._scope.toName(e);return this._for(new sg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=gr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),n(s)})}return this._for(new Du("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?gr.varKinds.var:gr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Du("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Po)}label(e){return this._leafNode(new Qh(e))}break(e){return this._leafNode(new eg(e))}return(e){let r=new oa;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(oa)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ig;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new sa(s),r(s)}return n&&(this._currNode=o.finally=new ia,this.code(n)),this._endBlockNode(sa,ia)}throw(e){return this._leafNode(new tg(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=pe.nil,n,o){return this._blockNode(new na(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(na)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof To))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};oe.CodeGen=ag;function Ro(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Mu(t,e){return e instanceof pe._CodeOrName?Ro(t,e.names):t}function $s(t,e,r){if(t instanceof pe.Name)return n(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function XD(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function l0(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${cg(t)}`}oe.not=l0;var QD=d0(oe.operators.AND);function eM(...t){return t.reduce(QD)}oe.and=eM;var tM=d0(oe.operators.OR);function rM(...t){return t.reduce(tM)}oe.or=rM;function d0(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${cg(e)} ${t} ${cg(r)}`}function cg(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=M(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var xe=ne(),nM=ta();function oM(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=oM;function sM(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(f0(t,e),!h0(e,t.self.RULES.all))}se.alwaysValidSchema=sM;function f0(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||_0(t,`unknown keyword: "${s}"`)}se.checkUnknownRules=f0;function h0(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=h0;function iM(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}se.schemaHasRulesButRef=iM;function aM({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,xe._)`${r}`}return(0,xe._)`${t}${e}${(0,xe.getProperty)(n)}`}se.schemaRefOrVal=aM;function cM(t){return g0(decodeURIComponent(t))}se.unescapeFragment=cM;function uM(t){return encodeURIComponent(lg(t))}se.escapeFragment=uM;function lg(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=lg;function g0(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=g0;function lM(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=lM;function p0({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof xe.Name?(s instanceof xe.Name?t(o,s,i):e(o,s,i),i):s instanceof xe.Name?(e(o,i,s),s):r(s,i);return a===xe.Name&&!(c instanceof xe.Name)?n(o,c):c}}se.mergeEvaluated={props:p0({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,xe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,xe._)`${r} || {}`).code((0,xe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,xe._)`${r} || {}`),dg(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:y0}),items:p0({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,xe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,xe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function y0(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,xe._)`{}`);return e!==void 0&&dg(t,r,e),r}se.evaluatedPropsToName=y0;function dg(t,e,r){Object.keys(r).forEach(n=>t.assign((0,xe._)`${e}${(0,xe.getProperty)(n)}`,!0))}se.setEvaluated=dg;var m0={};function dM(t,e){return t.scopeValue("func",{ref:e,code:m0[e.code]||(m0[e.code]=new nM._Code(e.code))})}se.useFunc=dM;var ug;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ug||(se.Type=ug={}));function pM(t,e,r){if(t instanceof xe.Name){let n=e===ug.Num;return r?n?(0,xe._)`"[" + ${t} + "]"`:(0,xe._)`"['" + ${t} + "']"`:n?(0,xe._)`"/" + ${t}`:(0,xe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,xe.getProperty)(t).toString():"/"+lg(t)}se.getErrorPath=pM;function _0(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}se.checkStrictMode=_0});var Xr=M(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var lt=ne(),mM={data:new lt.Name("data"),valCxt:new lt.Name("valCxt"),instancePath:new lt.Name("instancePath"),parentData:new lt.Name("parentData"),parentDataProperty:new lt.Name("parentDataProperty"),rootData:new lt.Name("rootData"),dynamicAnchors:new lt.Name("dynamicAnchors"),vErrors:new lt.Name("vErrors"),errors:new lt.Name("errors"),this:new lt.Name("this"),self:new lt.Name("self"),scope:new lt.Name("scope"),json:new lt.Name("json"),jsonPos:new lt.Name("jsonPos"),jsonLen:new lt.Name("jsonLen"),jsonPart:new lt.Name("jsonPart")};pg.default=mM});var aa=M(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.extendErrors=dt.resetErrorsCount=dt.reportExtraError=dt.reportError=dt.keyword$DataError=dt.keywordError=void 0;var fe=ne(),zu=me(),xt=Xr();dt.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};dt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function fM(t,e=dt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=x0(t,e,r);n??(i||a)?v0(s,c):b0(o,(0,fe._)`[${c}]`)}dt.reportError=fM;function hM(t,e=dt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=x0(t,e,r);v0(o,a),s||i||b0(n,xt.default.vErrors)}dt.reportExtraError=hM;function gM(t,e){t.assign(xt.default.errors,e),t.if((0,fe._)`${xt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${xt.default.vErrors}.length`,e),()=>t.assign(xt.default.vErrors,null)))}dt.resetErrorsCount=gM;function yM({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,xt.default.errors,a=>{t.const(i,(0,fe._)`${xt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(xt.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}dt.extendErrors=yM;function v0(t,e){let r=t.const("err",e);t.if((0,fe._)`${xt.default.vErrors} === null`,()=>t.assign(xt.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${xt.default.vErrors}.push(${r})`),t.code((0,fe._)`${xt.default.errors}++`)}function b0(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var Co={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function x0(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:_M(t,e,r)}function _M(t,e,r={}){let{gen:n,it:o}=t,s=[vM(o,r),bM(t,r)];return xM(t,e,s),n.object(...s)}function vM({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,zu.getErrorPath)(e,zu.Type.Str)}`:t;return[xt.default.instancePath,(0,fe.strConcat)(xt.default.instancePath,r)]}function bM({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,fe.str)`${e}/${t}`;return r&&(o=(0,fe.str)`${o}${(0,zu.getErrorPath)(r,zu.Type.Str)}`),[Co.schemaPath,o]}function xM(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([Co.keyword,o],[Co.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([Co.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Co.schema,i],[Co.parentSchema,(0,fe._)`${d}${l}`],[xt.default.data,s]),u&&n.push([Co.propertyName,u])}});var k0=M(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.boolOrEmptySchema=Ts.topBoolOrEmptySchema=void 0;var SM=aa(),kM=ne(),wM=Xr(),EM={message:"boolean schema is false"};function $M(t){let{gen:e,schema:r,validateName:n}=t;r===!1?S0(t,!1):typeof r=="object"&&r.$async===!0?e.return(wM.default.data):(e.assign((0,kM._)`${n}.errors`,null),e.return(!0))}Ts.topBoolOrEmptySchema=$M;function TM(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),S0(t)):r.var(e,!0)}Ts.boolOrEmptySchema=TM;function S0(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,SM.reportError)(o,EM,void 0,e)}});var mg=M(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.getRules=Ps.isJSONType=void 0;var PM=["string","number","integer","boolean","null","object","array"],RM=new Set(PM);function CM(t){return typeof t=="string"&&RM.has(t)}Ps.isJSONType=CM;function OM(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ps.getRules=OM});var fg=M(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.shouldUseRule=Cn.shouldUseGroup=Cn.schemaHasRulesForType=void 0;function IM({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&w0(t,n)}Cn.schemaHasRulesForType=IM;function w0(t,e){return e.rules.some(r=>E0(t,r))}Cn.shouldUseGroup=w0;function E0(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Cn.shouldUseRule=E0});var ca=M(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.reportTypeError=pt.checkDataTypes=pt.checkDataType=pt.coerceAndCheckDataType=pt.getJSONTypes=pt.getSchemaTypes=pt.DataType=void 0;var AM=mg(),NM=fg(),DM=aa(),ee=ne(),$0=me(),Rs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Rs||(pt.DataType=Rs={}));function MM(t){let e=T0(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}pt.getSchemaTypes=MM;function T0(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(AM.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}pt.getJSONTypes=T0;function jM(t,e){let{gen:r,data:n,opts:o}=t,s=zM(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,NM.schemaHasRulesForType)(t,e[0]));if(i){let a=gg(e,n,o.strictNumbers,Rs.Wrong);r.if(a,()=>{s.length?LM(t,e,s):yg(t)})}return i}pt.coerceAndCheckDataType=jM;var P0=new Set(["string","number","integer","boolean","null"]);function zM(t,e){return e?t.filter(r=>P0.has(r)||e==="array"&&r==="array"):[]}function LM(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ee._)`typeof ${o}`),a=n.let("coerced",(0,ee._)`undefined`);s.coerceTypes==="array"&&n.if((0,ee._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ee._)`${o}[0]`).assign(i,(0,ee._)`typeof ${o}`).if(gg(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(P0.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),yg(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(o,a),FM(t,a)});function c(u){switch(u){case"string":n.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${o}`).elseIf((0,ee._)`${o} === null`).assign(a,(0,ee._)`""`);return;case"number":n.elseIf((0,ee._)`${i} == "boolean" || ${o} === null
190
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ee._)`+${o}`);return;case"integer":n.elseIf((0,ee._)`${i} === "boolean" || ${o} === null
191
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ee._)`+${o}`);return;case"boolean":n.elseIf((0,ee._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ee._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ee._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ee._)`${i} === "string" || ${i} === "number"
192
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,ee._)`[${o}]`)}}}function FM({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function hg(t,e,r,n=Rs.Correct){let o=n===Rs.Correct?ee.operators.EQ:ee.operators.NEQ,s;switch(t){case"null":return(0,ee._)`${e} ${o} null`;case"array":s=(0,ee._)`Array.isArray(${e})`;break;case"object":s=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ee._)`typeof ${e} ${o} ${t}`}return n===Rs.Correct?s:(0,ee.not)(s);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,r?(0,ee._)`isFinite(${e})`:ee.nil)}}pt.checkDataType=hg;function gg(t,e,r,n){if(t.length===1)return hg(t[0],e,r,n);let o,s=(0,$0.toHash)(t);if(s.array&&s.object){let i=(0,ee._)`typeof ${e} != "object"`;o=s.null?i:(0,ee._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ee.nil;s.number&&delete s.integer;for(let i in s)o=(0,ee.and)(o,hg(i,e,r,n));return o}pt.checkDataTypes=gg;var UM={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function yg(t){let e=HM(t);(0,DM.reportError)(e,UM)}pt.reportTypeError=yg;function HM(t){let{gen:e,data:r,schema:n}=t,o=(0,$0.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var C0=M(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});Lu.assignDefaults=void 0;var Cs=ne(),ZM=me();function BM(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)R0(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>R0(t,s,o.default))}Lu.assignDefaults=BM;function R0(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Cs._)`${s}${(0,Cs.getProperty)(e)}`;if(o){(0,ZM.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Cs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Cs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Cs._)`${a} = ${(0,Cs.stringify)(r)}`)}});var tr=M(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var Re=ne(),_g=me(),On=Xr(),qM=me();function VM(t,e){let{gen:r,data:n,it:o}=t;r.if(bg(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}be.checkReportMissingProp=VM;function WM({gen:t,data:e,it:{opts:r}},n,o){return(0,Re.or)(...n.map(s=>(0,Re.and)(bg(t,e,s,r.ownProperties),(0,Re._)`${o} = ${s}`)))}be.checkMissingProp=WM;function GM(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=GM;function O0(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=O0;function vg(t,e,r){return(0,Re._)`${O0(t)}.call(${e}, ${r})`}be.isOwnProperty=vg;function KM(t,e,r,n){let o=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${o} && ${vg(t,e,r)}`:o}be.propertyInData=KM;function bg(t,e,r,n){let o=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(o,(0,Re.not)(vg(t,e,r))):o}be.noPropertyInData=bg;function I0(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=I0;function JM(t,e){return I0(e).filter(r=>!(0,_g.alwaysValidSchema)(t,e[r]))}be.schemaProperties=JM;function YM({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,Re._)`${t}, ${e}, ${n}${o}`:e,l=[[On.default.instancePath,(0,Re.strConcat)(On.default.instancePath,s)],[On.default.parentData,i.parentData],[On.default.parentDataProperty,i.parentDataProperty],[On.default.rootData,On.default.rootData]];i.opts.dynamicRef&&l.push([On.default.dynamicAnchors,On.default.dynamicAnchors]);let m=(0,Re._)`${d}, ${r.object(...l)}`;return c!==Re.nil?(0,Re._)`${a}.call(${c}, ${m})`:(0,Re._)`${a}(${m})`}be.callValidateCode=YM;var XM=(0,Re._)`new RegExp`;function QM({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Re._)`${o.code==="new RegExp"?XM:(0,qM.useFunc)(t,o)}(${r}, ${n})`})}be.usePattern=QM;function ej(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Re._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:_g.Type.Num},s),e.if((0,Re.not)(s),a)})}}be.validateArray=ej;function tj(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,_g.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Re._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Re.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=tj});var D0=M(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.validateKeywordUsage=Ar.validSchemaType=Ar.funcKeywordCode=Ar.macroKeywordCode=void 0;var St=ne(),Oo=Xr(),rj=tr(),nj=aa();function oj(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=N0(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:St.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ar.macroKeywordCode=oj;function sj(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;aj(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=N0(n,o,u),l=n.let("valid");t.block$data(l,m),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function m(){if(e.errors===!1)h(),e.modifying&&A0(t),g(()=>t.error());else{let y=e.async?f():p();e.modifying&&A0(t),g(()=>ij(t,y))}}function f(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,St._)`await `),v=>n.assign(l,!1).if((0,St._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,St._)`${v}.errors`),()=>n.throw(v))),y}function p(){let y=(0,St._)`${d}.errors`;return n.assign(y,null),h(St.nil),y}function h(y=e.async?(0,St._)`await `:St.nil){let v=c.opts.passContext?Oo.default.this:Oo.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,St._)`${y}${(0,rj.callValidateCode)(t,d,v,_)}`,e.modifying)}function g(y){var v;n.if((0,St.not)((v=e.valid)!==null&&v!==void 0?v:l),y)}}Ar.funcKeywordCode=sj;function A0(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,St._)`${n.parentData}[${n.parentDataProperty}]`))}function ij(t,e){let{gen:r}=t;r.if((0,St._)`Array.isArray(${e})`,()=>{r.assign(Oo.default.vErrors,(0,St._)`${Oo.default.vErrors} === null ? ${e} : ${Oo.default.vErrors}.concat(${e})`).assign(Oo.default.errors,(0,St._)`${Oo.default.vErrors}.length`),(0,nj.extendErrors)(t)},()=>t.error())}function aj({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function N0(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,St.stringify)(r)})}function cj(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ar.validSchemaType=cj;function uj({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ar.validateKeywordUsage=uj});var j0=M(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.extendSubschemaMode=In.extendSubschemaData=In.getSubschema=void 0;var Nr=ne(),M0=me();function lj(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Nr._)`${t.schemaPath}${(0,Nr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Nr._)`${t.schemaPath}${(0,Nr.getProperty)(e)}${(0,Nr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,M0.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}In.getSubschema=lj;function dj(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,m=a.let("data",(0,Nr._)`${e.data}${(0,Nr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Nr.str)`${u}${(0,M0.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Nr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Nr.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}In.extendSubschemaData=dj;function pj(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}In.extendSubschemaMode=pj});var xg=M((MW,z0)=>{"use strict";z0.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var F0=M((jW,L0)=>{"use strict";var An=L0.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Fu(e,n,o,t,"",t)};An.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};An.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};An.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};An.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Fu(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in An.arrayKeywords)for(var m=0;m<l.length;m++)Fu(t,e,r,l[m],o+"/"+d+"/"+m,s,o,d,n,m)}else if(d in An.propsKeywords){if(l&&typeof l=="object")for(var f in l)Fu(t,e,r,l[f],o+"/"+d+"/"+mj(f),s,o,d,n,f)}else(d in An.keywords||t.allKeys&&!(d in An.skipKeywords))&&Fu(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function mj(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ua=M(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.getSchemaRefs=At.resolveUrl=At.normalizeId=At._getFullPath=At.getFullPath=At.inlineRef=void 0;var fj=me(),hj=xg(),gj=F0(),yj=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _j(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Sg(t):e?U0(t)<=e:!1}At.inlineRef=_j;var vj=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Sg(t){for(let e in t){if(vj.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Sg)||typeof r=="object"&&Sg(r))return!0}return!1}function U0(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!yj.has(r)&&(typeof t[r]=="object"&&(0,fj.eachItem)(t[r],n=>e+=U0(n)),e===1/0))return 1/0}return e}function H0(t,e="",r){r!==!1&&(e=Os(e));let n=t.parse(e);return Z0(t,n)}At.getFullPath=H0;function Z0(t,e){return t.serialize(e).split("#")[0]+"#"}At._getFullPath=Z0;var bj=/#\/?$/;function Os(t){return t?t.replace(bj,""):""}At.normalizeId=Os;function xj(t,e,r){return r=Os(r),t.resolve(e,r)}At.resolveUrl=xj;var Sj=/^[a-z_][-a-z0-9._]*$/i;function kj(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Os(t[r]||e),s={"":o},i=H0(n,o,!1),a={},c=new Set;return gj(t,{allKeys:!0},(l,m,f,p)=>{if(p===void 0)return;let h=i+m,g=s[p];typeof l[r]=="string"&&(g=y.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),s[m]=g;function y(_){let b=this.opts.uriResolver.resolve;if(_=Os(g?b(g,_):_),c.has(_))throw d(_);c.add(_);let x=this.refs[_];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(l,x.schema,_):_!==Os(h)&&(_[0]==="#"?(u(l,a[_],_),a[_]=l):this.refs[_]=h),_}function v(_){if(typeof _=="string"){if(!Sj.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(l,m,f){if(m!==void 0&&!hj(l,m))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}At.getSchemaRefs=kj});var pa=M(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.getData=Nn.KeywordCxt=Nn.validateFunctionCode=void 0;var G0=k0(),B0=ca(),wg=fg(),Uu=ca(),wj=C0(),da=D0(),kg=j0(),V=ne(),X=Xr(),Ej=ua(),Qr=me(),la=aa();function $j(t){if(Y0(t)&&(X0(t),J0(t))){Rj(t);return}K0(t,()=>(0,G0.topBoolOrEmptySchema)(t))}Nn.validateFunctionCode=$j;function K0({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,V._)`${X.default.data}, ${X.default.valCxt}`,n.$async,()=>{t.code((0,V._)`"use strict"; ${q0(r,o)}`),Pj(t,o),t.code(s)}):t.func(e,(0,V._)`${X.default.data}, ${Tj(o)}`,n.$async,()=>t.code(q0(r,o)).code(s))}function Tj(t){return(0,V._)`{${X.default.instancePath}="", ${X.default.parentData}, ${X.default.parentDataProperty}, ${X.default.rootData}=${X.default.data}${t.dynamicRef?(0,V._)`, ${X.default.dynamicAnchors}={}`:V.nil}}={}`}function Pj(t,e){t.if(X.default.valCxt,()=>{t.var(X.default.instancePath,(0,V._)`${X.default.valCxt}.${X.default.instancePath}`),t.var(X.default.parentData,(0,V._)`${X.default.valCxt}.${X.default.parentData}`),t.var(X.default.parentDataProperty,(0,V._)`${X.default.valCxt}.${X.default.parentDataProperty}`),t.var(X.default.rootData,(0,V._)`${X.default.valCxt}.${X.default.rootData}`),e.dynamicRef&&t.var(X.default.dynamicAnchors,(0,V._)`${X.default.valCxt}.${X.default.dynamicAnchors}`)},()=>{t.var(X.default.instancePath,(0,V._)`""`),t.var(X.default.parentData,(0,V._)`undefined`),t.var(X.default.parentDataProperty,(0,V._)`undefined`),t.var(X.default.rootData,X.default.data),e.dynamicRef&&t.var(X.default.dynamicAnchors,(0,V._)`{}`)})}function Rj(t){let{schema:e,opts:r,gen:n}=t;K0(t,()=>{r.$comment&&e.$comment&&ew(t),Nj(t),n.let(X.default.vErrors,null),n.let(X.default.errors,0),r.unevaluated&&Cj(t),Q0(t),jj(t)})}function Cj(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,V._)`${r}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function q0(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${r} */`:V.nil}function Oj(t,e){if(Y0(t)&&(X0(t),J0(t))){Ij(t,e);return}(0,G0.boolOrEmptySchema)(t,e)}function J0({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Y0(t){return typeof t.schema!="boolean"}function Ij(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&ew(t),Dj(t),Mj(t);let s=n.const("_errs",X.default.errors);Q0(t,s),n.var(e,(0,V._)`${s} === ${X.default.errors}`)}function X0(t){(0,Qr.checkUnknownRules)(t),Aj(t)}function Q0(t,e){if(t.opts.jtd)return V0(t,[],!1,e);let r=(0,B0.getSchemaTypes)(t.schema),n=(0,B0.coerceAndCheckDataType)(t,r);V0(t,r,!n,e)}function Aj(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Qr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Nj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Qr.checkStrictMode)(t,"default is ignored in the schema root")}function Dj(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Ej.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Mj(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function ew({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,V._)`${X.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${X.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function jj(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,V._)`${X.default.errors} === 0`,()=>e.return(X.default.data),()=>e.throw((0,V._)`new ${o}(${X.default.vErrors})`)):(e.assign((0,V._)`${n}.errors`,X.default.vErrors),s.unevaluated&&zj(t),e.return((0,V._)`${X.default.errors} === 0`))}function zj({gen:t,evaluated:e,props:r,items:n}){r instanceof V.Name&&t.assign((0,V._)`${e}.props`,r),n instanceof V.Name&&t.assign((0,V._)`${e}.items`,n)}function V0(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Qr.schemaHasRulesButRef)(s,d))){o.block(()=>rw(t,"$ref",d.all.$ref.definition));return}c.jtd||Lj(t,e),o.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,wg.shouldUseGroup)(s,m)&&(m.type?(o.if((0,Uu.checkDataType)(m.type,i,c.strictNumbers)),W0(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,Uu.reportTypeError)(t)),o.endIf()):W0(t,m),a||o.if((0,V._)`${X.default.errors} === ${n||0}`))}}function W0(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,wj.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,wg.shouldUseRule)(n,s)&&rw(t,s.keyword,s.definition,e.type)})}function Lj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Fj(t,e),t.opts.allowUnionTypes||Uj(t,e),Hj(t,t.dataTypes))}function Fj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{tw(t.dataTypes,r)||Eg(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Bj(t,e)}}function Uj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Eg(t,"use allowUnionTypes to allow union type keyword")}function Hj(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,wg.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Zj(e,i))&&Eg(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Zj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function tw(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Bj(t,e){let r=[];for(let n of t.dataTypes)tw(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Eg(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Qr.checkStrictMode)(t,e,t.opts.strictTypes)}var Hu=class{constructor(e,r,n){if((0,da.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Qr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",nw(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,da.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",X.default.errors))}result(e,r,n){this.failResult((0,V.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,V.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,V._)`${r} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?la.reportExtraError:la.reportError)(this,this.def.error,r)}$dataError(){(0,la.reportError)(this,this.def.$dataError||la.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,la.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=V.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=V.nil,r=V.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,V.or)((0,V._)`${o} === undefined`,r)),e!==V.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(n.length){if(!(r instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,V._)`${(0,Uu.checkDataTypes)(c,r,s.opts.strictNumbers,Uu.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${r})`}return V.nil}}subschema(e,r){let n=(0,kg.getSubschema)(this.it,e);(0,kg.extendSubschemaData)(n,this.it,e),(0,kg.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Oj(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Qr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Qr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,V.Name)),!0}};Nn.KeywordCxt=Hu;function rw(t,e,r,n){let o=new Hu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,da.funcKeywordCode)(o,r):"macro"in r?(0,da.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,da.funcKeywordCode)(o,r)}var qj=/^\/(?:[^~]|~0|~1)*$/,Vj=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function nw(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return X.default.rootData;if(t[0]==="/"){if(!qj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=X.default.rootData}else{let u=Vj.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(o=u[2],o==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=r[e-d],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,V._)`${s}${(0,V.getProperty)((0,Qr.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Nn.getData=nw});var Zu=M(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var $g=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Tg.default=$g});var ma=M(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var Pg=ua(),Rg=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Pg.resolveUrl)(e,r,n),this.missingSchema=(0,Pg.normalizeId)((0,Pg.getFullPath)(e,this.missingRef))}};Cg.default=Rg});var qu=M(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.resolveSchema=rr.getCompilingSchema=rr.resolveRef=rr.compileSchema=rr.SchemaEnv=void 0;var yr=ne(),Wj=Zu(),Io=Xr(),_r=ua(),ow=me(),Gj=pa(),Is=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,_r.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};rr.SchemaEnv=Is;function Ig(t){let e=sw.call(this,t);if(e)return e;let r=(0,_r.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new yr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Wj.default,code:(0,yr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Io.default.data,parentData:Io.default.parentData,parentDataProperty:Io.default.parentDataProperty,dataNames:[Io.default.data],dataPathArr:[yr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,yr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:yr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,yr._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,Gj.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(Io.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${Io.default.self}`,`${Io.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;f.evaluated={props:p instanceof yr.Name?void 0:p,items:h instanceof yr.Name?void 0:h,dynamicProps:p instanceof yr.Name,dynamicItems:h instanceof yr.Name},f.source&&(f.source.evaluated=(0,yr.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}rr.compileSchema=Ig;function Kj(t,e,r){var n;r=(0,_r.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Xj.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Is({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Jj.call(this,s)}rr.resolveRef=Kj;function Jj(t){return(0,_r.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ig.call(this,t)}function sw(t){for(let e of this._compilations)if(Yj(e,t))return e}rr.getCompilingSchema=sw;function Yj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Xj(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Bu.call(this,t,e)}function Bu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,_r._getFullPath)(this.opts.uriResolver,r),o=(0,_r.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Og.call(this,r,t);let s=(0,_r.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Bu.call(this,t,i);return typeof a?.schema!="object"?void 0:Og.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ig.call(this,i),s===(0,_r.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,_r.resolveUrl)(this.opts.uriResolver,o,u)),new Is({schema:a,schemaId:c,root:t,baseId:o})}return Og.call(this,r,i)}}rr.resolveSchema=Bu;var Qj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Og(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,ow.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Qj.has(a)&&u&&(e=(0,_r.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,ow.schemaHasRulesButRef)(r,this.RULES)){let a=(0,_r.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Bu.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Is({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var iw=M((ZW,ez)=>{ez.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ng=M((BW,lw)=>{"use strict";var tz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),cw=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Ag(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var rz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function aw(t){return t.length=0,!0}function nz(t,e,r){if(t.length){let n=Ag(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function oz(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=nz;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=aw}else{o.push(u);continue}}return o.length&&(a===aw?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ag(o))),r.address=n.join(""),r}function uw(t){if(sz(t,":")<2)return{host:t,isIPV6:!1};let e=oz(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function sz(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function iz(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function az(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function cz(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!cw(r)){let n=uw(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}lw.exports={nonSimpleDomain:rz,recomposeAuthority:cz,normalizeComponentEncoding:az,removeDotSegments:iz,isIPv4:cw,isUUID:tz,normalizeIPv6:uw,stringArrayToHexStripped:Ag}});var hw=M((qW,fw)=>{"use strict";var{isUUID:uz}=Ng(),lz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,dz=["http","https","ws","wss","urn","urn:uuid"];function pz(t){return dz.indexOf(t)!==-1}function Dg(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function dw(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function pw(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function mz(t){return t.secure=Dg(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function fz(t){if((t.port===(Dg(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function hz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(lz);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Mg(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function gz(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Mg(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function yz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!uz(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function _z(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var mw={scheme:"http",domainHost:!0,parse:dw,serialize:pw},vz={scheme:"https",domainHost:mw.domainHost,parse:dw,serialize:pw},Vu={scheme:"ws",domainHost:!0,parse:mz,serialize:fz},bz={scheme:"wss",domainHost:Vu.domainHost,parse:Vu.parse,serialize:Vu.serialize},xz={scheme:"urn",parse:hz,serialize:gz,skipNormalize:!0},Sz={scheme:"urn:uuid",parse:yz,serialize:_z,skipNormalize:!0},Wu={http:mw,https:vz,ws:Vu,wss:bz,urn:xz,"urn:uuid":Sz};Object.setPrototypeOf(Wu,null);function Mg(t){return t&&(Wu[t]||Wu[t.toLowerCase()])||void 0}fw.exports={wsIsSecure:Dg,SCHEMES:Wu,isValidSchemeName:pz,getSchemeHandler:Mg}});var _w=M((VW,Ku)=>{"use strict";var{normalizeIPv6:kz,removeDotSegments:fa,recomposeAuthority:wz,normalizeComponentEncoding:Gu,isIPv4:Ez,nonSimpleDomain:$z}=Ng(),{SCHEMES:Tz,getSchemeHandler:gw}=hw();function Pz(t,e){return typeof t=="string"?t=Dr(en(t,e),e):typeof t=="object"&&(t=en(Dr(t,e),e)),t}function Rz(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=yw(en(t,n),en(e,n),n,!0);return n.skipEscape=!0,Dr(o,n)}function yw(t,e,r,n){let o={};return n||(t=en(Dr(t,r),r),e=en(Dr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=fa(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=fa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=fa(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=fa(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function Cz(t,e,r){return typeof t=="string"?(t=unescape(t),t=Dr(Gu(en(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Dr(Gu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Dr(Gu(en(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Dr(Gu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Dr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=gw(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=wz(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=fa(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var Oz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function en(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(Oz);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(Ez(n.host)===!1){let c=kz(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=gw(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&$z(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var jg={SCHEMES:Tz,normalize:Pz,resolve:Rz,resolveComponent:yw,equal:Cz,serialize:Dr,parse:en};Ku.exports=jg;Ku.exports.default=jg;Ku.exports.fastUri=jg});var bw=M(zg=>{"use strict";Object.defineProperty(zg,"__esModule",{value:!0});var vw=_w();vw.code='require("ajv/dist/runtime/uri").default';zg.default=vw});var Pw=M(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.CodeGen=it.Name=it.nil=it.stringify=it.str=it._=it.KeywordCxt=void 0;var Iz=pa();Object.defineProperty(it,"KeywordCxt",{enumerable:!0,get:function(){return Iz.KeywordCxt}});var As=ne();Object.defineProperty(it,"_",{enumerable:!0,get:function(){return As._}});Object.defineProperty(it,"str",{enumerable:!0,get:function(){return As.str}});Object.defineProperty(it,"stringify",{enumerable:!0,get:function(){return As.stringify}});Object.defineProperty(it,"nil",{enumerable:!0,get:function(){return As.nil}});Object.defineProperty(it,"Name",{enumerable:!0,get:function(){return As.Name}});Object.defineProperty(it,"CodeGen",{enumerable:!0,get:function(){return As.CodeGen}});var Az=Zu(),Ew=ma(),Nz=mg(),ha=qu(),Dz=ne(),ga=ua(),Ju=ca(),Fg=me(),xw=iw(),Mz=bw(),$w=(t,e)=>new RegExp(t,e);$w.code="new RegExp";var jz=["removeAdditional","useDefaults","coerceTypes"],zz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Lz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Fz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Sw=200;function Uz(t){var e,r,n,o,s,i,a,c,u,d,l,m,f,p,h,g,y,v,_,b,x,P,E,R,A;let L=t.strict,w=(e=t.code)===null||e===void 0?void 0:e.optimize,F=w===!0||w===void 0?1:w||0,U=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:$w,te=(o=t.uriResolver)!==null&&o!==void 0?o:Mz.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:L)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:L)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:L)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:L)!==null&&m!==void 0?m:"log",strictRequired:(p=(f=t.strictRequired)!==null&&f!==void 0?f:L)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:F,regExp:U}:{optimize:F,regExp:U},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Sw,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Sw,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(E=t.validateFormats)!==null&&E!==void 0?E:!0,unicodeRegExp:(R=t.unicodeRegExp)!==null&&R!==void 0?R:!0,int32range:(A=t.int32range)!==null&&A!==void 0?A:!0,uriResolver:te}}var ya=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Uz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Dz.ValueScope({scope:{},prefixes:zz,es5:r,lines:n}),this.logger=Wz(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Nz.getRules)(),kw.call(this,Lz,e,"NOT SUPPORTED"),kw.call(this,Fz,e,"DEPRECATED","warn"),this._metaOpts=qz.call(this),e.formats&&Zz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Bz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Hz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=xw;n==="id"&&(o={...xw},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await s.call(this,d.$schema);let m=this._addSchema(d,l);return m.validate||i.call(this,m)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Ew.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ga.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ww.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ha.SchemaEnv({schema:{},schemaId:n});if(r=ha.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ww.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,ga.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Kz.call(this,n,r),!r)return(0,Fg.eachItem)(n,s=>Lg.call(this,s)),this;Yz.call(this,r);let o={...r,type:(0,Ju.getJSONTypes)(r.type),schemaType:(0,Ju.getJSONTypes)(r.schemaType)};return(0,Fg.eachItem)(n,o.type.length===0?s=>Lg.call(this,s,o):s=>o.type.forEach(i=>Lg.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=Tw(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,ga.normalizeId)(i||n);let u=ga.getSchemaRefs.call(this,e,n);return c=new ha.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ha.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{ha.compileSchema.call(this,e)}finally{this.opts=r}}};ya.ValidationError=Az.default;ya.MissingRefError=Ew.default;it.default=ya;function kw(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function ww(t){return t=(0,ga.normalizeId)(t),this.schemas[t]||this.refs[t]}function Hz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Zz(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Bz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function qz(){let t={...this.opts};for(let e of jz)delete t[e];return t}var Vz={log(){},warn(){},error(){}};function Wz(t){if(t===!1)return Vz;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Gz=/^[a-z_$][a-z0-9_$:-]*$/i;function Kz(t,e){let{RULES:r}=this;if((0,Fg.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Gz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Lg(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Ju.getJSONTypes)(e.type),schemaType:(0,Ju.getJSONTypes)(e.schemaType)}};e.before?Jz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Jz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Yz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Tw(e)),t.validateSchema=this.compile(e,!0))}var Xz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Tw(t){return{anyOf:[t,Xz]}}});var Rw=M(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});var Qz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ug.default=Qz});var Aw=M(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.callRef=Ao.getValidate=void 0;var eL=ma(),Cw=tr(),Nt=ne(),Ns=Xr(),Ow=qu(),Yu=me(),tL={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=Ow.resolveRef.call(c,u,o,r);if(d===void 0)throw new eL.default(n.opts.uriResolver,o,r);if(d instanceof Ow.SchemaEnv)return m(d);return f(d);function l(){if(s===u)return Xu(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return Xu(t,(0,Nt._)`${p}.validate`,u,u.$async)}function m(p){let h=Iw(t,p);Xu(t,h,p,p.$async)}function f(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Nt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:Nt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function Iw(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Nt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ao.getValidate=Iw;function Xu(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Ns.default.this:Nt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,Nt._)`await ${(0,Cw.callValidateCode)(t,e,u)}`),f(e),i||o.assign(p,!0)},h=>{o.if((0,Nt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),m(h),i||o.assign(p,!1)}),t.ok(p)}function l(){t.result((0,Cw.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(p){let h=(0,Nt._)`${p}.errors`;o.assign(Ns.default.vErrors,(0,Nt._)`${Ns.default.vErrors} === null ? ${h} : ${Ns.default.vErrors}.concat(${h})`),o.assign(Ns.default.errors,(0,Nt._)`${Ns.default.vErrors}.length`)}function f(p){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Yu.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,Nt._)`${p}.evaluated.props`);s.props=Yu.mergeEvaluated.props(o,y,s.props,Nt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Yu.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,Nt._)`${p}.evaluated.items`);s.items=Yu.mergeEvaluated.items(o,y,s.items,Nt.Name)}}}Ao.callRef=Xu;Ao.default=tL});var Nw=M(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var rL=Rw(),nL=Aw(),oL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rL.default,nL.default];Hg.default=oL});var Dw=M(Zg=>{"use strict";Object.defineProperty(Zg,"__esModule",{value:!0});var Qu=ne(),Dn=Qu.operators,el={maximum:{okStr:"<=",ok:Dn.LTE,fail:Dn.GT},minimum:{okStr:">=",ok:Dn.GTE,fail:Dn.LT},exclusiveMaximum:{okStr:"<",ok:Dn.LT,fail:Dn.GTE},exclusiveMinimum:{okStr:">",ok:Dn.GT,fail:Dn.LTE}},sL={message:({keyword:t,schemaCode:e})=>(0,Qu.str)`must be ${el[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Qu._)`{comparison: ${el[t].okStr}, limit: ${e}}`},iL={keyword:Object.keys(el),type:"number",schemaType:"number",$data:!0,error:sL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Qu._)`${r} ${el[e].fail} ${n} || isNaN(${r})`)}};Zg.default=iL});var Mw=M(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var _a=ne(),aL={message:({schemaCode:t})=>(0,_a.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,_a._)`{multipleOf: ${t}}`},cL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:aL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,_a._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,_a._)`${i} !== parseInt(${i})`;t.fail$data((0,_a._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Bg.default=cL});var zw=M(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});function jw(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}qg.default=jw;jw.code='require("ajv/dist/runtime/ucs2length").default'});var Lw=M(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var No=ne(),uL=me(),lL=zw(),dL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,No.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,No._)`{limit: ${t}}`},pL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:dL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?No.operators.GT:No.operators.LT,i=o.opts.unicode===!1?(0,No._)`${r}.length`:(0,No._)`${(0,uL.useFunc)(t.gen,lL.default)}(${r})`;t.fail$data((0,No._)`${i} ${s} ${n}`)}};Vg.default=pL});var Fw=M(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});var mL=tr(),fL=me(),Ds=ne(),hL={message:({schemaCode:t})=>(0,Ds.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ds._)`{pattern: ${t}}`},gL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:hL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Ds._)`new RegExp`:(0,fL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Ds._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Ds._)`!${d}`)}else{let c=(0,mL.usePattern)(t,o);t.fail$data((0,Ds._)`!${c}.test(${r})`)}}};Wg.default=gL});var Uw=M(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});var va=ne(),yL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,va.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,va._)`{limit: ${t}}`},_L={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:yL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?va.operators.GT:va.operators.LT;t.fail$data((0,va._)`Object.keys(${r}).length ${o} ${n}`)}};Gg.default=_L});var Hw=M(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var ba=tr(),xa=ne(),vL=me(),bL={message:({params:{missingProperty:t}})=>(0,xa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,xa._)`{missingProperty: ${t}}`},xL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:bL,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(f?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,vL.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(xa.nil,l);else for(let f of r)(0,ba.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>m(f,p)),t.ok(p)}else e.if((0,ba.checkMissingProp)(t,r,f)),(0,ba.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,ba.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function m(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,ba.propertyInData)(e,o,f,a.ownProperties)),e.if((0,xa.not)(p),()=>{t.error(),e.break()})},xa.nil)}}};Kg.default=xL});var Zw=M(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var Sa=ne(),SL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Sa.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Sa._)`{limit: ${t}}`},kL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:SL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Sa.operators.GT:Sa.operators.LT;t.fail$data((0,Sa._)`${r}.length ${o} ${n}`)}};Jg.default=kL});var tl=M(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var Bw=xg();Bw.code='require("ajv/dist/runtime/equal").default';Yg.default=Bw});var qw=M(Qg=>{"use strict";Object.defineProperty(Qg,"__esModule",{value:!0});var Xg=ca(),at=ne(),wL=me(),EL=tl(),$L={message:({params:{i:t,j:e}})=>(0,at.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,at._)`{i: ${t}, j: ${e}}`},TL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:$L,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Xg.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,at._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,at._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,at._)`${p} > 1`,()=>(l()?m:f)(p,h))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,h){let g=e.name("item"),y=(0,Xg.checkDataTypes)(u,g,a.opts.strictNumbers,Xg.DataType.Wrong),v=e.const("indices",(0,at._)`{}`);e.for((0,at._)`;${p}--;`,()=>{e.let(g,(0,at._)`${r}[${p}]`),e.if(y,(0,at._)`continue`),u.length>1&&e.if((0,at._)`typeof ${g} == "string"`,(0,at._)`${g} += "_"`),e.if((0,at._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,at._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,at._)`${v}[${g}] = ${p}`)})}function f(p,h){let g=(0,wL.useFunc)(e,EL.default),y=e.name("outer");e.label(y).for((0,at._)`;${p}--;`,()=>e.for((0,at._)`${h} = ${p}; ${h}--;`,()=>e.if((0,at._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Qg.default=TL});var Vw=M(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});var ey=ne(),PL=me(),RL=tl(),CL={message:"must be equal to constant",params:({schemaCode:t})=>(0,ey._)`{allowedValue: ${t}}`},OL={keyword:"const",$data:!0,error:CL,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,ey._)`!${(0,PL.useFunc)(e,RL.default)}(${r}, ${o})`):t.fail((0,ey._)`${s} !== ${r}`)}};ty.default=OL});var Ww=M(ry=>{"use strict";Object.defineProperty(ry,"__esModule",{value:!0});var ka=ne(),IL=me(),AL=tl(),NL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ka._)`{allowedValues: ${t}}`},DL={keyword:"enum",schemaType:"array",$data:!0,error:NL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,IL.useFunc)(e,AL.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);d=(0,ka.or)(...o.map((p,h)=>m(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,f=>e.if((0,ka._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,p){let h=o[p];return typeof h=="object"&&h!==null?(0,ka._)`${u()}(${r}, ${f}[${p}])`:(0,ka._)`${r} === ${h}`}}};ry.default=DL});var Gw=M(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});var ML=Dw(),jL=Mw(),zL=Lw(),LL=Fw(),FL=Uw(),UL=Hw(),HL=Zw(),ZL=qw(),BL=Vw(),qL=Ww(),VL=[ML.default,jL.default,zL.default,LL.default,FL.default,UL.default,HL.default,ZL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},BL.default,qL.default];ny.default=VL});var sy=M(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.validateAdditionalItems=void 0;var Do=ne(),oy=me(),WL={message:({params:{len:t}})=>(0,Do.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Do._)`{limit: ${t}}`},GL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:WL,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,oy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Kw(t,n)}};function Kw(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Do._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Do._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,oy.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Do._)`${a} <= ${e.length}`);r.if((0,Do.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:oy.Type.Num},u),i.allErrors||r.if((0,Do.not)(u),()=>r.break())})}}wa.validateAdditionalItems=Kw;wa.default=GL});var iy=M(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.validateTuple=void 0;var Jw=ne(),rl=me(),KL=tr(),JL={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Yw(t,"additionalItems",e);r.items=!0,!(0,rl.alwaysValidSchema)(r,e)&&t.ok((0,KL.validateArray)(t))}};function Yw(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=rl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Jw._)`${s}.length`);r.forEach((l,m)=>{(0,rl.alwaysValidSchema)(a,l)||(n.if((0,Jw._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:f}=a,p=r.length,h=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,rl.checkStrictMode)(a,g,m.strictTuples)}}}Ea.validateTuple=Yw;Ea.default=JL});var Xw=M(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});var YL=iy(),XL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,YL.validateTuple)(t,"items")};ay.default=XL});var eE=M(cy=>{"use strict";Object.defineProperty(cy,"__esModule",{value:!0});var Qw=ne(),QL=me(),eF=tr(),tF=sy(),rF={message:({params:{len:t}})=>(0,Qw.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Qw._)`{limit: ${t}}`},nF={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rF,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,QL.alwaysValidSchema)(n,e)&&(o?(0,tF.validateAdditionalItems)(t,o):t.ok((0,eF.validateArray)(t)))}};cy.default=nF});var tE=M(uy=>{"use strict";Object.defineProperty(uy,"__esModule",{value:!0});var nr=ne(),nl=me(),oF={message:({params:{min:t,max:e}})=>e===void 0?(0,nr.str)`must contain at least ${t} valid item(s)`:(0,nr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,nr._)`{minContains: ${t}}`:(0,nr._)`{minContains: ${t}, maxContains: ${e}}`},sF={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:oF,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,nr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,nl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,nl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,nl.alwaysValidSchema)(s,r)){let h=(0,nr._)`${d} >= ${i}`;a!==void 0&&(h=(0,nr._)`${h} && ${d} <= ${a}`),t.pass(h);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,nr._)`${o}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>p(g)))}function f(h,g){e.forRange("i",0,d,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:nl.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,nr._)`${h}++`),a===void 0?e.if((0,nr._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,nr._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,nr._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};uy.default=sF});var oE=M(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.validateSchemaDeps=Mr.validatePropertyDeps=Mr.error=void 0;var ly=ne(),iF=me(),$a=tr();Mr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ly.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ly._)`{property: ${t},
193
- missingProperty: ${n},
194
- depsCount: ${e},
195
- deps: ${r}}`};var aF={keyword:"dependencies",type:"object",schemaType:"object",error:Mr.error,code(t){let[e,r]=cF(t);rE(t,e),nE(t,r)}};function cF({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function rE(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,$a.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,$a.checkReportMissingProp)(t,u)}):(r.if((0,ly._)`${c} && (${(0,$a.checkMissingProp)(t,a,s)})`),(0,$a.reportMissingProp)(t,s),r.else())}}Mr.validatePropertyDeps=rE;function nE(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,iF.alwaysValidSchema)(s,e[a])||(r.if((0,$a.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Mr.validateSchemaDeps=nE;Mr.default=aF});var iE=M(dy=>{"use strict";Object.defineProperty(dy,"__esModule",{value:!0});var sE=ne(),uF=me(),lF={message:"property name must be valid",params:({params:t})=>(0,sE._)`{propertyName: ${t.propertyName}}`},dF={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:lF,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,uF.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,sE.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};dy.default=dF});var my=M(py=>{"use strict";Object.defineProperty(py,"__esModule",{value:!0});var ol=tr(),vr=ne(),pF=Xr(),sl=me(),mF={message:"must NOT have additional properties",params:({params:t})=>(0,vr._)`{additionalProperty: ${t.additionalProperty}}`},fF={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mF,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,sl.alwaysValidSchema)(i,r))return;let u=(0,ol.allSchemaProperties)(n.properties),d=(0,ol.allSchemaProperties)(n.patternProperties);l(),t.ok((0,vr._)`${s} === ${pF.default.errors}`);function l(){e.forIn("key",o,g=>{!u.length&&!d.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let v=(0,sl.schemaRefOrVal)(i,n.properties,"properties");y=(0,ol.isOwnProperty)(e,v,g)}else u.length?y=(0,vr.or)(...u.map(v=>(0,vr._)`${g} === ${v}`)):y=vr.nil;return d.length&&(y=(0,vr.or)(y,...d.map(v=>(0,vr._)`${(0,ol.usePattern)(t,v)}.test(${g})`))),(0,vr.not)(y)}function f(g){e.code((0,vr._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,sl.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,vr.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,vr.not)(y),()=>e.break()))}}function h(g,y,v){let _={keyword:"additionalProperties",dataProp:g,dataPropType:sl.Type.Str};v===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};py.default=fF});var uE=M(hy=>{"use strict";Object.defineProperty(hy,"__esModule",{value:!0});var hF=pa(),aE=tr(),fy=me(),cE=my(),gF={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&cE.default.code(new hF.KeywordCxt(s,cE.default,"additionalProperties"));let i=(0,aE.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=fy.mergeEvaluated.props(e,(0,fy.toHash)(i),s.props));let a=i.filter(l=>!(0,fy.alwaysValidSchema)(s,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,aE.propertyInData)(e,o,l,s.opts.ownProperties)),d(l),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};hy.default=gF});var mE=M(gy=>{"use strict";Object.defineProperty(gy,"__esModule",{value:!0});var lE=tr(),il=ne(),dE=me(),pE=me(),yF={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,lE.allSchemaProperties)(r),c=a.filter(h=>(0,dE.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof il.Name)&&(s.props=(0,pE.evaluatedPropsToName)(e,s.props));let{props:l}=s;m();function m(){for(let h of a)u&&f(h),s.allErrors?p(h):(e.var(d,!0),p(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,dE.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,il._)`${(0,lE.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:pE.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,il._)`${l}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,il.not)(d),()=>e.break())})})}}};gy.default=yF});var fE=M(yy=>{"use strict";Object.defineProperty(yy,"__esModule",{value:!0});var _F=me(),vF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,_F.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};yy.default=vF});var hE=M(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});var bF=tr(),xF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:bF.validateUnion,error:{message:"must match a schema in anyOf"}};_y.default=xF});var gE=M(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});var al=ne(),SF=me(),kF={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,al._)`{passingSchemas: ${t.passing}}`},wF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kF,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let m;(0,SF.alwaysValidSchema)(o,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,al._)`${c} && ${i}`).assign(i,!1).assign(a,(0,al._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,al.Name)})})}}};vy.default=wF});var yE=M(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});var EF=me(),$F={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,EF.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};by.default=$F});var bE=M(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});var cl=ne(),vE=me(),TF={message:({params:t})=>(0,cl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,cl._)`{failingKeyword: ${t.ifClause}}`},PF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:TF,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,vE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=_E(n,"then"),s=_E(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else o?e.if(a,u("then")):e.if((0,cl.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let m=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(m,i),l?e.assign(l,(0,cl._)`${d}`):t.setParams({ifClause:d})}}}};function _E(t,e){let r=t.schema[e];return r!==void 0&&!(0,vE.alwaysValidSchema)(t,r)}xy.default=PF});var xE=M(Sy=>{"use strict";Object.defineProperty(Sy,"__esModule",{value:!0});var RF=me(),CF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,RF.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Sy.default=CF});var SE=M(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var OF=sy(),IF=Xw(),AF=iy(),NF=eE(),DF=tE(),MF=oE(),jF=iE(),zF=my(),LF=uE(),FF=mE(),UF=fE(),HF=hE(),ZF=gE(),BF=yE(),qF=bE(),VF=xE();function WF(t=!1){let e=[UF.default,HF.default,ZF.default,BF.default,qF.default,VF.default,jF.default,zF.default,MF.default,LF.default,FF.default];return t?e.push(IF.default,NF.default):e.push(OF.default,AF.default),e.push(DF.default),e}ky.default=WF});var kE=M(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var Ve=ne(),GF={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},KF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:GF,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?m():f();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,Ve._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ve._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Ve._)`${h}.type || "string"`).assign(y,(0,Ve._)`${h}.validate`),()=>r.assign(g,(0,Ve._)`"string"`).assign(y,h)),t.fail$data((0,Ve.or)(v(),_()));function v(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${y}`}function _(){let b=d.$async?(0,Ve._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ve._)`${y}(${n})`,x=(0,Ve._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${n}))`;return(0,Ve._)`${y} && ${y} !== true && ${g} === ${e} && !${x}`}}function f(){let p=l.formats[s];if(!p){v();return}if(p===!0)return;let[h,g,y]=_(p);h===e&&t.pass(b());function v(){if(c.strictSchema===!1){l.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(x){let P=x instanceof RegExp?(0,Ve.regexpCode)(x):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,E=r.scopeValue("formats",{key:s,ref:x,code:P});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Ve._)`${E}.validate`]:["string",x,E]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${y}(${n})`}return typeof g=="function"?(0,Ve._)`${y}(${n})`:(0,Ve._)`${y}.test(${n})`}}}};wy.default=KF});var wE=M(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});var JF=kE(),YF=[JF.default];Ey.default=YF});var EE=M(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.contentVocabulary=Ms.metadataVocabulary=void 0;Ms.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ms.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var TE=M($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});var XF=Nw(),QF=Gw(),e2=SE(),t2=wE(),$E=EE(),r2=[XF.default,QF.default,(0,e2.default)(),t2.default,$E.metadataVocabulary,$E.contentVocabulary];$y.default=r2});var RE=M(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.DiscrError=void 0;var PE;(function(t){t.Tag="tag",t.Mapping="mapping"})(PE||(ul.DiscrError=PE={}))});var OE=M(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var js=ne(),Ty=RE(),CE=qu(),n2=ma(),o2=me(),s2={message:({params:{discrError:t,tagName:e}})=>t===Ty.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,js._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},i2={keyword:"discriminator",type:"object",schemaType:"object",error:s2,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,js._)`${r}${(0,js.getProperty)(a)}`);e.if((0,js._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Ty.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=m();e.if(!1);for(let p in f)e.elseIf((0,js._)`${u} === ${p}`),e.assign(c,l(f[p]));e.else(),t.error(!1,{discrError:Ty.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(h,js.Name),p}function m(){var f;let p={},h=y(o),g=!0;for(let b=0;b<i.length;b++){let x=i[b];if(x?.$ref&&!(0,o2.schemaHasRulesButRef)(x,s.self.RULES)){let E=x.$ref;if(x=CE.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,E),x instanceof CE.SchemaEnv&&(x=x.schema),x===void 0)throw new n2.default(s.opts.uriResolver,s.baseId,E)}let P=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(x)),v(P,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,x){if(b.const)_(b.const,x);else if(b.enum)for(let P of b.enum)_(P,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(b,x){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=x}}}};Py.default=i2});var IE=M((NG,a2)=>{a2.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Cy=M((Ce,Ry)=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.MissingRefError=Ce.ValidationError=Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=Ce.Ajv=void 0;var c2=Pw(),u2=TE(),l2=OE(),AE=IE(),d2=["/properties"],ll="http://json-schema.org/draft-07/schema",zs=class extends c2.default{_addVocabularies(){super._addVocabularies(),u2.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(l2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(AE,d2):AE;this.addMetaSchema(e,ll,!1),this.refs["http://json-schema.org/schema"]=ll}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ll)?ll:void 0)}};Ce.Ajv=zs;Ry.exports=Ce=zs;Ry.exports.Ajv=zs;Object.defineProperty(Ce,"__esModule",{value:!0});Ce.default=zs;var p2=pa();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return p2.KeywordCxt}});var Ls=ne();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return Ls._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return Ls.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return Ls.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return Ls.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return Ls.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return Ls.CodeGen}});var m2=Zu();Object.defineProperty(Ce,"ValidationError",{enumerable:!0,get:function(){return m2.default}});var f2=ma();Object.defineProperty(Ce,"MissingRefError",{enumerable:!0,get:function(){return f2.default}})});var UE=M(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.formatNames=zr.fastFormats=zr.fullFormats=void 0;function jr(t,e){return{validate:t,compare:e}}zr.fullFormats={date:jr(jE,Ny),time:jr(Iy(!0),Dy),"date-time":jr(NE(!0),LE),"iso-time":jr(Iy(),zE),"iso-date-time":jr(NE(),FE),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:b2,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((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})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((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})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((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}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((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}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((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}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((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}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((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}))|:)))$/i,regex:T2,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:x2,int32:{type:"number",validate:w2},int64:{type:"number",validate:E2},float:{type:"number",validate:ME},double:{type:"number",validate:ME},password:!0,binary:!0};zr.fastFormats={...zr.fullFormats,date:jr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ny),time:jr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Dy),"date-time":jr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,LE),"iso-time":jr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,zE),"iso-date-time":jr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,FE),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};zr.formatNames=Object.keys(zr.fullFormats);function h2(t){return t%4===0&&(t%100!==0||t%400===0)}var g2=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,y2=[0,31,28,31,30,31,30,31,31,30,31,30,31];function jE(t){let e=g2.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&h2(r)?29:y2[n])}function Ny(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Oy=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Iy(t){return function(r){let n=Oy.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,m=o-u*c-(l<0?1:0);return(m===23||m===-1)&&(l===59||l===-1)&&i<61}}function Dy(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function zE(t,e){if(!(t&&e))return;let r=Oy.exec(t),n=Oy.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Ay=/t|\s/i;function NE(t){let e=Iy(t);return function(n){let o=n.split(Ay);return o.length===2&&jE(o[0])&&e(o[1])}}function LE(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function FE(t,e){if(!(t&&e))return;let[r,n]=t.split(Ay),[o,s]=e.split(Ay),i=Ny(r,o);if(i!==void 0)return i||Dy(n,s)}var _2=/\/|:/,v2=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function b2(t){return _2.test(t)&&v2.test(t)}var DE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function x2(t){return DE.lastIndex=0,DE.test(t)}var S2=-(2**31),k2=2**31-1;function w2(t){return Number.isInteger(t)&&t<=k2&&t>=S2}function E2(t){return Number.isInteger(t)}function ME(){return!0}var $2=/[^\\]\\Z/;function T2(t){if($2.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var HE=M(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.formatLimitDefinition=void 0;var P2=Cy(),br=ne(),Mn=br.operators,dl={formatMaximum:{okStr:"<=",ok:Mn.LTE,fail:Mn.GT},formatMinimum:{okStr:">=",ok:Mn.GTE,fail:Mn.LT},formatExclusiveMaximum:{okStr:"<",ok:Mn.LT,fail:Mn.GTE},formatExclusiveMinimum:{okStr:">",ok:Mn.GT,fail:Mn.LTE}},R2={message:({keyword:t,schemaCode:e})=>(0,br.str)`should be ${dl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,br._)`{comparison: ${dl[t].okStr}, limit: ${e}}`};Fs.formatLimitDefinition={keyword:Object.keys(dl),type:"string",schemaType:"string",$data:!0,error:R2,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new P2.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,br._)`${m}[${c.schemaCode}]`);t.fail$data((0,br.or)((0,br._)`typeof ${f} != "object"`,(0,br._)`${f} instanceof RegExp`,(0,br._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,br._)`${i.code.formats}${(0,br.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,br._)`${m}.compare(${r}, ${n}) ${dl[o].fail} 0`}},dependencies:["format"]};var C2=t=>(t.addKeyword(Fs.formatLimitDefinition),t);Fs.default=C2});var VE=M((Ta,qE)=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});var Us=UE(),O2=HE(),My=ne(),ZE=new My.Name("fullFormats"),I2=new My.Name("fastFormats"),jy=(t,e={keywords:!0})=>{if(Array.isArray(e))return BE(t,e,Us.fullFormats,ZE),t;let[r,n]=e.mode==="fast"?[Us.fastFormats,I2]:[Us.fullFormats,ZE],o=e.formats||Us.formatNames;return BE(t,o,r,n),e.keywords&&(0,O2.default)(t),t};jy.get=(t,e="full")=>{let n=(e==="fast"?Us.fastFormats:Us.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function BE(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,My._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}qE.exports=Ta=jy;Object.defineProperty(Ta,"__esModule",{value:!0});Ta.default=jy});function A2(){let t=new WE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,GE.default)(t),t}var WE,GE,pl,KE=S(()=>{WE=ei(Cy(),1),GE=ei(VE(),1);pl=class{constructor(e){this._ajv=e??A2()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var ml,JE=S(()=>{Eo();ml=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(d=>d.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(d=>d.type==="tool_use");if(i){if(s.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Yi,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},ws,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function YE(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function XE(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var QE=S(()=>{});var fl,e$=S(()=>{a0();Eo();KE();Li();JE();QE();fl=class extends Cu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ji.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new pl,this.setRequestHandler(Xf,n=>this._oninitialize(n)),this.setNotificationHandler(Qf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ih,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ji.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ml(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=i0(this._capabilities,e)}setRequestHandler(e,r){let o=En(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Jt(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let d=wn(ks,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new Z(W.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=wn(ys,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new Z(W.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let f=wn(_u,m);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new Z(W.InvalidParams,`Invalid tools/call result: ${p}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){XE(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&YE(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:ik.includes(r)?r:Wf,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},iu)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(o.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},ah,r):this.request({method:"sampling/createMessage",params:e},Yi,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},ws,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},ws,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(W.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(W.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},ch,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function zy(t){return!!t&&typeof t=="object"&&r$ in t}function n$(t){return t[r$]?.complete}var r$,t$,o$=S(()=>{r$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(t$||(t$={}))});var s$=S(()=>{});function D2(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!N2.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function M2(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Ly(t){let e=D2(t);return M2(t,e.warnings),e.isValid}var N2,i$=S(()=>{N2=/^[A-Za-z0-9._-]{1,128}$/});var hl,a$=S(()=>{hl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Fy=S(()=>{Cc();Cc()});function l$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function d$(t){return"_def"in t||"_zod"in t||l$(t)}function Uy(t){return typeof t!="object"||t===null||d$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(l$)}function c$(t){if(t){if(Uy(t))return wo(t);if(!d$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function z2(t){let e=En(t);return e?Object.entries(e).map(([r,n])=>{let o=OS(n),s=IS(n);return{name:r,description:o,required:!s}}):[]}function jn(t){let r=En(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=eu(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function u$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var gl,j2,Pa,p$=S(()=>{e$();Li();qh();Eo();o$();s$();i$();a$();Fy();gl=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new fl(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new hl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(Ss)),this.server.assertCanSetRequestHandler(jn(ks)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ss,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=hs(r.inputSchema);return o?Hh(o,{strictUnions:!0,pipeStrategy:"input"}):j2})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=hs(r.outputSchema);o&&(n.outputSchema=Hh(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(ks,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Z(W.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Z(W.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new Z(W.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(W.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof Z&&n.code===W.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=hs(e.inputSchema)??e.inputSchema,i=await Xc(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Qc(a);throw new Z(W.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(W.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=hs(e.outputSchema),s=await Xc(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Qc(i);throw new Z(W.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,d));let l=await n.taskStore.getTask(c);if(!l)throw new Z(W.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(jn(vu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(vu,async e=>{switch(e.params.ref.type){case"ref/prompt":return Sk(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return kk(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(W.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(W.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(W.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Pa;let s=En(n.argsSchema)?.[e.params.argument.name];if(!zy(s))return Pa;let i=n$(s);if(!i)return Pa;let a=await i(e.params.argument.value,e.params.context);return u$(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Pa;throw new Z(W.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Pa;let s=await o(e.params.argument.value,e.params.context);return u$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(vs)),this.server.assertCanSetRequestHandler(jn(bs)),this.server.assertCanSetRequestHandler(jn(gu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(vs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(bs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(gu,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(W.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new Z(W.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(xs)),this.server.assertCanSetRequestHandler(jn(yu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?z2(r.argsSchema):void 0}))})),this.server.setRequestHandler(yu,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Z(W.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Z(W.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=hs(n.argsSchema),s=await Xc(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Qc(c);throw new Z(W.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:wo(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=wo(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Pt?c._def?.innerType:c;return zy(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Ly(e);let d={title:r,description:n,inputSchema:c$(o),outputSchema:c$(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Ly(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=wo(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=wo(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Uy(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Uy(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},j2={type:"object",properties:{}};Pa={completion:{values:[],hasMore:!1}}});function L2(t){return fk.parse(JSON.parse(t))}function m$(t){return JSON.stringify(t)+`
196
- `}var yl,f$=S(()=>{Eo();yl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
197
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),L2(r)}clear(){this._buffer=void 0}}});import h$ from"node:process";var _l,g$=S(()=>{f$();_l=class{constructor(e=h$.stdin,r=h$.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new yl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=m$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var $$={};Le($$,{PolyglotExecutor:()=>Hs,buildScriptFilename:()=>k$,buildShellScriptContent:()=>E$,buildSpawnOptions:()=>w$});import{spawn as y$,execSync as F2,execFileSync as x$}from"node:child_process";import{mkdtempSync as U2,writeFileSync as _$,rmSync as v$,existsSync as b$}from"node:fs";import{join as vl,resolve as S$}from"node:path";import{tmpdir as H2}from"node:os";function k$(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${Z2[t]}`}function w$(t){return{windowsHide:t==="win32"}}function B2(t){return`'${t.replace(/'/g,"'\\''")}'`}function E$(t,e,r){return r==="win32"||!e?t:`export PATH=${B2(e)}
198
- ${t}`}function Hy(t){if(or&&t.pid)try{F2(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var or,Z2,q2,Hs,Zy=S(()=>{"use strict";Qa();or=process.platform==="win32",Z2={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};q2=(()=>{if(or)return process.env.TEMP??process.env.TMP??H2();try{let t=x$(process.platform==="darwin"?"getconf":"mktemp",process.platform==="darwin"?["DARWIN_USER_TEMP_DIR"]:["-u","-d"],{env:{...process.env,TMPDIR:void 0},encoding:"utf-8"}).trim(),e=process.platform==="darwin"?t:S$(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();Hs=class{#e;#t;#n;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Lo()}get#o(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(or?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:o,background:s=!1,cwd:i}=e,a=U2(vl(q2,".ctx-mode-"));try{let c=this.#a(a,n,r),u=J_(this.#n,r,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let d=r==="shell"?i??this.#o:a,l=await this.#i(u,d,a,o,s);if(!l.backgrounded)try{v$(a,{recursive:!0,force:!0})}catch{}return l}catch(c){try{v$(a,{recursive:!0,force:!0})}catch{}throw c}}async executeFile(e){let{path:r,language:n,code:o,timeout:s}=e,i=S$(this.#o,r),a=this.#l(i,n,o);return this.execute({language:n,code:a,timeout:s})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
139
+ `,d=u.text.endsWith(`
140
+ `)?u.text:`${u.text}${l}`;lp(dp(a),{recursive:!0}),wx(a,d,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{NO(r,MO.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=jO(dp(LO(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return ms(e,"utf-8")}catch{return`# context-mode
199
141
 
200
- import "fmt"
142
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return no(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return DO(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(ms(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();lp(dp(r),{recursive:!0}),wx(r,JSON.stringify(e,null,2)+`
143
+ `,"utf-8")}upsertManagedHookEntry(e,r,n,o){let s=Array.isArray(e[r])?[...e[r]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(n),e[r]=s,o.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(n)&&(s[a]=n,o.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${r} context-mode hook`);e[r]=s}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(oo[e]??""),s=FO[e]??[];return n.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as Cx,writeFileSync as BO,mkdirSync as ZO,accessSync as qO,chmodSync as VO,constants as WO}from"node:fs";import{resolve as Oc,join as KO}from"node:path";var fs,mp=S(()=>{"use strict";pt();fs=class extends be{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return Oc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=Cx(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=Cx(Oc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();ZO(Oc(".github","hooks"),{recursive:!0}),BO(r,JSON.stringify(e,null,2)+`
144
+ `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=KO(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Oc(n,o);try{qO(s,WO.R_OK),VO(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function Ox(t,e){if(!fp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,fp,$9,T9,Ix=S(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},fp={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},$9=[Yt.PRE_TOOL_USE,Yt.SESSION_START],T9=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var Nx={};we(Nx,{VSCodeCopilotAdapter:()=>yp});import{readFileSync as hp,mkdirSync as Ax,accessSync as GO,existsSync as JO,constants as XO}from"node:fs";import{resolve as hs,join as Ai}from"node:path";import{homedir as gp}from"node:os";var yp,Dx=S(()=>{"use strict";mp();pt();Ix();yp=class extends fs{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:fp,buildHookCommand:Ox};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=Pt();if(e){let s=Ai(e,"context-mode","sessions");return Ax(s,{recursive:!0}),s}let r=hs(".github","context-mode","sessions"),n=Ai(gp(),".vscode","context-mode","sessions"),o=JO(hs(".github"))?r:n;return Ax(o,{recursive:!0}),o}getConfigDir(e){return hs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=hs(".github","hooks");try{GO(n,XO.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=hs(n,"context-mode.json");try{let s=hp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=hs(".vscode","mcp.json"),r=hp(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Ai(gp(),".vscode","extensions"),Ai(gp(),".vscode-insiders","extensions")];for(let r of e)try{let n=hp(Ai(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function Mx(t,e){if(!_p[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,_p,D9,M9,jx=S(()=>{"use strict";Qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},_p={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},D9=[Qt.PRE_TOOL_USE,Qt.SESSION_START],M9=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var Lx={};we(Lx,{JetBrainsCopilotAdapter:()=>bp});import{readFileSync as YO}from"node:fs";import{resolve as QO}from"node:path";var bp,zx=S(()=>{"use strict";mp();jx();bp=class extends fs{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:_p,buildHookCommand:Mx};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return QO(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=YO(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Qt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Ni(t,e){let r=xp[e],n=er(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function er(t){return`context-mode hook cursor ${t.toLowerCase()}`}var xe,xp,eI,tI,vp,Fx,Hx,Ux=S(()=>{"use strict";xe={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},xp={[xe.PRE_TOOL_USE]:"pretooluse.mjs",[xe.POST_TOOL_USE]:"posttooluse.mjs",[xe.SESSION_START]:"sessionstart.mjs",[xe.STOP]:"stop.mjs",[xe.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},eI="MCP:(?!ctx_)",tI=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",eI],vp=tI.join("|"),Fx=[xe.PRE_TOOL_USE],Hx=[xe.POST_TOOL_USE]});var Wx={};we(Wx,{CursorAdapter:()=>Sp});import{readFileSync as Ic,writeFileSync as rI,mkdirSync as nI,accessSync as Bx,chmodSync as oI,constants as Zx,existsSync as qx,readdirSync as sI}from"node:fs";import{execSync as iI}from"node:child_process";import{resolve as so,join as io}from"node:path";import{homedir as Ac}from"node:os";var Vx,Sp,Kx=S(()=>{"use strict";pt();kn();Ux();Vx="/Library/Application Support/Cursor/hooks.json",Sp=class extends be{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return so(".cursor","hooks.json")}getConfigDir(e){return so(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[xe.PRE_TOOL_USE]:[{type:"command",command:er(xe.PRE_TOOL_USE),matcher:vp,loop_limit:null,failClosed:!1}],[xe.POST_TOOL_USE]:[{type:"command",command:er(xe.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[xe.SESSION_START]:[{type:"command",command:er(xe.SESSION_START),loop_limit:null,failClosed:!1}],[xe.STOP]:[{type:"command",command:er(xe.STOP),loop_limit:null,failClosed:!1}],[xe.AFTER_AGENT_RESPONSE]:[{type:"command",command:er(xe.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ic(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();nI(so(".cursor"),{recursive:!0}),rI(r,JSON.stringify(e,null,2)+`
145
+ `,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of Fx){let a=s[i],c=Array.isArray(a)&&a.some(u=>Ni(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of Hx){let a=s[i],c=Array.isArray(a)&&a.some(u=>Ni(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}qx(Vx)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Ni(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),r}detectPluginInstalls(){let e=[io(Ac(),".cursor","plugins","local"),io(Ac(),".cursor","plugins","cache")],r=[];for(let n of e){try{Bx(n,Zx.F_OK)}catch{continue}let o=[];try{o=sI(n)}catch{continue}for(let s of o){let i=io(n,s,".cursor-plugin","plugin.json");try{let a=Ic(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[so(".cursor","mcp.json"),io(Ac(),".cursor","mcp.json")];for(let n of e)try{let o=Ic(n,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return iI("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},o=[];return this.upsertHookEntry(n,xe.PRE_TOOL_USE,{type:"command",command:er(xe.PRE_TOOL_USE),matcher:vp,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,xe.POST_TOOL_USE,{type:"command",command:er(xe.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,xe.SESSION_START,{type:"command",command:er(xe.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,xe.STOP,{type:"command",command:er(xe.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,xe.AFTER_AGENT_RESPONSE,{type:"command",command:er(xe.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),r.version=1,r.hooks=n,this.writeSettings(r),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let r=[],n=io(e,"hooks","cursor");for(let o of Object.values(xp)){let s=so(n,o);try{Bx(s,Zx.R_OK),oI(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),io(Ac(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(Vx),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ic(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[so(".claude","settings.json"),so(".claude","settings.local.json"),io(qe(),"settings.json")].some(r=>qx(r))}upsertHookEntry(e,r,n,o){let s=e[r],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Ni(c,r));a>=0?(i[a]=n,o.push(`Updated existing ${r} hook entry`)):(i.push(n),o.push(`Added ${r} hook entry`)),e[r]=i}}});var Jx={};we(Jx,{AntigravityAdapter:()=>wp});import{readFileSync as Nc,writeFileSync as aI,mkdirSync as cI}from"node:fs";import{resolve as Dc,dirname as Gx}from"node:path";import{fileURLToPath as uI}from"node:url";import{homedir as kp}from"node:os";var wp,Xx=S(()=>{"use strict";pt();wp=class extends be{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Dc(kp(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Dc(kp(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Nc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();cI(Gx(r),{recursive:!0}),aI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Nc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=Dc(kp(),".gemini","extensions","context-mode","package.json");return JSON.parse(Nc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Dc(Gx(uI(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Nc(e,"utf-8")}catch{return`# context-mode
201
146
 
202
- func main() {
203
- ${r}
204
- }
205
- `),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
206
- ${r}`),n==="elixir"&&b$(vl(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(vl(this.#o,"_build/dev/lib"))}, "*/ebin"))
207
- |> Enum.each(&Code.prepend_path/1)
147
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function Mc(t,e){let r=Yx[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function gs(t,e){let r=Yx[t];return e&&r?Xe(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var He,Yx,lI,dI,Ep,nV,oV,Qx=S(()=>{"use strict";Cr();He={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},Yx={[He.PRE_TOOL_USE]:"pretooluse.mjs",[He.POST_TOOL_USE]:"posttooluse.mjs",[He.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[He.AGENT_SPAWN]:"agentspawn.mjs"},lI="@(?!context-mode/)",dI=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",lI],Ep=dI.join("|"),nV=[He.PRE_TOOL_USE,He.AGENT_SPAWN],oV=[He.POST_TOOL_USE,He.USER_PROMPT_SUBMIT]});var nv={};we(nv,{KiroAdapter:()=>$p});import{readFileSync as ys,writeFileSync as ev,mkdirSync as tv}from"node:fs";import{resolve as ao,dirname as rv}from"node:path";import{fileURLToPath as pI}from"node:url";import{homedir as jc}from"node:os";var $p,ov=S(()=>{"use strict";pt();Qx();$p=class extends be{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return ao(jc(),".kiro","settings","mcp.json")}getConfigDir(e){return ao(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[He.PRE_TOOL_USE]:[{matcher:Ep,hooks:[{type:"command",command:gs(He.PRE_TOOL_USE,e)}]}],[He.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:gs(He.POST_TOOL_USE,e)}]}],[He.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:gs(He.AGENT_SPAWN,e)}]}],[He.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:gs(He.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=ys(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();tv(rv(r),{recursive:!0}),ev(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=ao(jc(),".kiro","agents","default.json");try{let s=JSON.parse(ys(n,"utf-8")).hooks??{};for(let i of[He.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Mc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[He.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>Mc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=ys(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=ao(jc(),".kiro","extensions","context-mode","package.json");return JSON.parse(ys(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=ao(jc(),".kiro","agents"),o=ao(n,"default.json");try{tv(n,{recursive:!0});let s={};try{s=JSON.parse(ys(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[He.PRE_TOOL_USE,Ep],[He.POST_TOOL_USE,"*"],[He.AGENT_SPAWN,"*"],[He.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Mc(d,c))||(l.push({matcher:u,command:gs(c,e)}),i[c]=l,r.push(`Added ${c} hook to ${o}`))}s.hooks=i,ev(o,JSON.stringify(s,null,2),"utf-8")}catch(s){r.push(`Failed to configure hooks: ${s.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=ao(rv(pI(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return ys(e,"utf-8")}catch{return`# context-mode
208
148
 
209
- ${r}`);let o=vl(e,k$(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?_$(o,E$(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):_$(o,r,"utf-8"),o}async#c(e,r,n){let o=or?".exe":"",s=e.replace(/\.rs$/,"")+o;try{x$("rustc",[e,"-o",s],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
210
- ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=or&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;or&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=or?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let d={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!or,...w$(process.platform)},l;if(a){let _=[c,...u].map(b=>/\s/.test(b)?JSON.stringify(b):b).join(" ");l=y$(_,[],{...d,shell:!0})}else l=y$(c,u,{...d,shell:!1});let m=!1,f=!1,p=o===void 0?void 0:setTimeout(()=>{if(m=!0,s){f=!0,l.pid&&this.#s.add(l.pid),l.unref(),l.stdout.destroy(),l.stderr.destroy();let _=Buffer.concat(h).toString("utf-8"),b=Buffer.concat(g).toString("utf-8");i({stdout:_,stderr:b,exitCode:0,timedOut:!0,backgrounded:!0})}else Hy(l)},o),h=[],g=[],y=0,v=!1;l.stdout.on("data",_=>{y+=_.length,y<=this.#e?h.push(_):v||(v=!0,Hy(l))}),l.stderr.on("data",_=>{y+=_.length,y<=this.#e?g.push(_):v||(v=!0,Hy(l))}),l.on("close",_=>{if(clearTimeout(p),f)return;let b=Buffer.concat(h).toString("utf-8"),x=Buffer.concat(g).toString("utf-8");v&&(x+=`
211
- [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:b,stderr:x,exitCode:m?1:_??1,timedOut:m})}),l.on("error",_=>{clearTimeout(p),!f&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!n.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=r,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",or&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=or?"":"/usr/local/bin:/usr/bin:/bin"),or){o.MSYS_NO_PATHCONV="1",o.MSYS2_ARG_CONV_EXCL="*";let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=or?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(b$(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,r,n){let o=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
212
- const file_path = FILE_CONTENT_PATH;
213
- const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
214
- ${n}`;case"python":return`FILE_CONTENT_PATH = ${o}
215
- file_path = FILE_CONTENT_PATH
216
- with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
217
- FILE_CONTENT = _f.read()
218
- ${n}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
219
- file_path=${s}
220
- FILE_CONTENT=$(cat ${s})
221
- ${n}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
222
- file_path = FILE_CONTENT_PATH
223
- FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
224
- ${n}`;case"go":return`package main
149
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var av={};we(av,{ZedAdapter:()=>Pp});import{readFileSync as Tp,writeFileSync as mI,mkdirSync as fI}from"node:fs";import{resolve as sv,dirname as iv}from"node:path";import{fileURLToPath as hI}from"node:url";import{homedir as gI}from"node:os";var Pp,cv=S(()=>{"use strict";pt();Pp=class extends be{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return sv(gI(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Tp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();fI(iv(r),{recursive:!0}),mI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Tp(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=sv(iv(hI(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Tp(e,"utf-8")}catch{return`# context-mode
225
150
 
226
- import (
227
- "fmt"
228
- "os"
229
- )
151
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var Rp,uv=S(()=>{"use strict";Rp="mcp__(?!.*context-mode)"});var pv={};we(pv,{QwenCodeAdapter:()=>Cp});import{readFileSync as yI,writeFileSync as _I,existsSync as bI}from"node:fs";import{resolve as lv,join as xI}from"node:path";import{homedir as dv}from"node:os";var Cp,mv=S(()=>{"use strict";Wd();uv();Cr();Cp=class extends ls{constructor(){super([".qwen"])}name="Qwen Code";paradigm="json-stdio";projectDirEnvVar="QWEN_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getSettingsPath(){return lv(dv(),".qwen","settings.json")}getInstructionFiles(){return["QWEN.md"]}generateHookConfig(e){return{PreToolUse:[{matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",Rp].join("|"),hooks:[{type:"command",command:Xe(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:Xe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=yI(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){_I(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;r.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(r))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let m=l.hooks??[];return m.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?m.every(p=>{if(!p.command)return!0;let f=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=f||g;return y?bI(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",Rp].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Xe(`${e}/hooks/${a}`)}]},l=n[i];if(l&&Array.isArray(l)){let d=l.findIndex(m=>m.hooks?.some(p=>p.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),n[i]=l}else n[i]=[u],o.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:lv(xI(dv(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var fv={};we(fv,{OMPAdapter:()=>Ap});import{readFileSync as Op,writeFileSync as vI,mkdirSync as SI}from"node:fs";import{resolve as Ip,dirname as kI}from"node:path";import{homedir as wI}from"node:os";var Ap,hv=S(()=>{"use strict";pt();Ap=class extends be{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??Ip(wI(),".omp","agent")}getSettingsPath(){return Ip(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Op(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();SI(kI(r),{recursive:!0}),vI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=Op(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:`Add context-mode to mcpServers in ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){try{let e=Ip(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(Op(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
230
152
 
231
- var FILE_CONTENT_PATH = ${o}
232
- var file_path = FILE_CONTENT_PATH
153
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var gv={};we(gv,{PiAdapter:()=>jp});import{readFileSync as Np,writeFileSync as EI,mkdirSync as $I}from"node:fs";import{resolve as Dp,dirname as TI}from"node:path";import{homedir as Mp}from"node:os";var jp,yv=S(()=>{"use strict";pt();jp=class extends be{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Dp(Mp(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Np(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();$I(TI(r),{recursive:!0}),EI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=Dp(Mp(),".pi","extensions","context-mode","package.json");try{return JSON.parse(Np(e,"utf-8"))?.name==="context-mode"?{check:"Pi extension registration",status:"pass",message:`context-mode extension installed at ${e}`}:{check:"Pi extension registration",status:"warn",message:`Unexpected package at ${e}`}}catch{return{check:"Pi extension registration",status:"fail",message:`context-mode not found at ${e}`,fix:"Run: context-mode upgrade"}}}getInstalledVersion(){try{let e=Dp(Mp(),".pi","extensions","context-mode","package.json");return JSON.parse(Np(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
233
154
 
234
- func main() {
235
- b, _ := os.ReadFile(FILE_CONTENT_PATH)
236
- FILE_CONTENT := string(b)
237
- _ = FILE_CONTENT
238
- _ = fmt.Sprint()
239
- ${n}
240
- }
241
- `;case"rust":return`#![allow(unused_variables)]
242
- use std::fs;
155
+ Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as _v}from"node:os";import{resolve as Lp}from"node:path";function bv(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?Lp(_v(),t.replace(/^~[/\\]?/,"")):Lp(t):Lp(_v(),".kimi-code")}var xv=S(()=>{"use strict"});var Ev={};we(Ev,{KimiAdapter:()=>Fp,probeKimiCliVersion:()=>wv});import{execFileSync as PI}from"node:child_process";import{readFileSync as Di,writeFileSync as RI,accessSync as CI,copyFileSync as OI,constants as II,mkdirSync as vv}from"node:fs";import{resolve as AI,dirname as Sv,join as co}from"node:path";import{fileURLToPath as NI}from"node:url";function wv(t=PI){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","kimi --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("kimi",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),r=String(e).trim();return r.length>0?r:"available (version output empty)"}catch{return null}}function kv(t){let e=[],r=t.split(/\r?\n/),n=null;for(let o of r){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){n&&n.event&&n.command&&e.push(n),n={};continue}if(!n)continue;let s=o.match(/^\s*(\w+)\s*=\s*(?:"([^"]*)"|(\d+))\s*(?:#.*)?$/);if(s){let i=s[1],a=s[2],c=s[3];a!==void 0?n[i]=a:c!==void 0&&(n[i]=Number(c))}}return n&&n.event&&n.command&&e.push(n),e}function jI(t){let e=["[[hooks]]"];return e.push(`event = "${t.event}"`),t.matcher&&e.push(`matcher = "${t.matcher}"`),e.push(`command = "${t.command}"`),t.timeout!==void 0&&e.push(`timeout = ${t.timeout}`),e.join(`
156
+ `)}function zp(t){return t.command.includes("context-mode hook kimi")}function LI(t,e){let r=(e.hooks?.[0]?.command??"").trim();return r?{event:t,matcher:e.matcher||void 0,command:r,timeout:30}:null}var DI,En,MI,Fp,$v=S(()=>{"use strict";pt();Jt();xv();DI="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",En={PreToolUse:"context-mode hook kimi pretooluse",PostToolUse:"context-mode hook kimi posttooluse",SessionStart:"context-mode hook kimi sessionstart",SessionEnd:"context-mode hook kimi sessionend",PreCompact:"context-mode hook kimi precompact",UserPromptSubmit:"context-mode hook kimi userpromptsubmit",Stop:"context-mode hook kimi stop"},MI={PreToolUse:["hooks/pretooluse.mjs","hooks/kimi/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/kimi/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/kimi/sessionstart.mjs"],SessionEnd:["hooks/sessionend.mjs","hooks/kimi/sessionend.mjs"],PreCompact:["hooks/precompact.mjs","hooks/kimi/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/kimi/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/kimi/stop.mjs"]};Fp=class extends be{constructor(){super([".kimi-code"])}name="Kimi Code CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,o=(r.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return bv()}getSettingsPath(){return co(this.getConfigDir(),"config.toml")}getMcpPath(){return co(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=Pt(),r=e?co(e,"context-mode","sessions"):co(this.getConfigDir(),"context-mode","sessions");return vv(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=Pt(),n=r?co(r,"context-mode","memory"):co(this.getConfigDir(),"memory");return e?co(n,nt(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:DI,hooks:[{type:"command",command:En.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:En.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:En.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:En.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:En.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:En.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:En.Stop}]}]}}readSettings(){try{return{_raw_toml:Di(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=wv();r.push({check:"Kimi Code CLI binary",status:n?"pass":"warn",message:n?`kimi --version resolved to ${n}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...n?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=Di(this.getSettingsPath(),"utf-8")}catch{return r.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),r}let s=kv(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(m=>m.event===a&&this.isExpectedHookEntry(a,m,u)),d=a==="PreCompact"?"warn":"fail";r.push({check:`${a} hook`,status:l?"pass":d,message:l?`${a} hook configured in ${this.getSettingsPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Kimi build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:l?void 0:`Update ${this.getSettingsPath()} to include the managed ${a} [[hooks]] entry`})}for(let a of Object.keys(i)){let c=s.filter(u=>u.event===a&&zp(u)).length;c>1&&r.push({check:`${a} duplicates`,status:"warn",message:`${c} context-mode entries found for ${a} in ${this.getSettingsPath()}; Kimi will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return r}checkPluginRegistration(){try{let e=Di(this.getMcpPath(),"utf-8"),r=JSON.parse(e),n=e.includes("context-mode"),o=r.mcpServers!==void 0||r.mcp_servers!==void 0;return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in mcp.json"}:o?{check:"MCP registration",status:"fail",message:"mcpServers section exists but context-mode not found",fix:`Add context-mode to mcpServers in ${this.getMcpPath()}`}:{check:"MCP registration",status:"fail",message:"No mcpServers section in mcp.json",fix:`Add mcpServers.context-mode to ${this.getMcpPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getMcpPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=[],n=this.generateHookConfig(""),o="";try{o=Di(this.getSettingsPath(),"utf-8")}catch{o=""}let s=kv(o),i=s.filter(l=>!zp(l)),a=[];for(let[l,d]of Object.entries(n)){let m=LI(l,d[0]);m&&a.push(m)}let c=s.some(zp),u=this.rebuildToml(o,i,a);return u!==o&&(vv(Sv(this.getSettingsPath()),{recursive:!0}),RI(this.getSettingsPath(),u,"utf-8"),c?r.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):r.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),r}backupSettings(){let e=null;for(let r of[this.getSettingsPath(),this.getMcpPath()])try{CI(r,II.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=AI(Sv(NI(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return Di(e,"utf-8")}catch{return`# context-mode
243
157
 
244
- fn main() {
245
- let file_content_path = ${o};
246
- let file_path = file_content_path;
247
- let file_content = fs::read_to_string(file_content_path).unwrap();
248
- ${n}
249
- }
250
- `;case"php":return`<?php
251
- $FILE_CONTENT_PATH = ${o};
252
- $file_path = $FILE_CONTENT_PATH;
253
- $FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
254
- ${n}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
255
- my $file_path = $FILE_CONTENT_PATH;
256
- open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
257
- my $FILE_CONTENT = do { local $/; <$fh> };
258
- close($fh);
259
- ${n}`;case"r":return`FILE_CONTENT_PATH <- ${o}
260
- file_path <- FILE_CONTENT_PATH
261
- FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
262
- FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
263
- ${n}`;case"elixir":return`file_content_path = ${o}
264
- file_path = file_content_path
265
- file_content = File.read!(file_content_path)
266
- ${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
267
- var file_path = FILE_CONTENT_PATH;
268
- var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
269
- ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,r),i=n?Math.max(1,V2().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),d=0;async function l(){for(;;){let f=d++;if(f>=t.length)return;try{let p=await t[f].run();u[f]={status:"fulfilled",value:p}}catch(p){u[f]={status:"rejected",reason:p}}o?.(f,u[f])}}let m=[];for(let f=0;f<a;f++)m.push(l());return await Promise.allSettled(m),{settled:u,effectiveConcurrency:a,capped:c}}var T$=S(()=>{"use strict"});import{readdirSync as W2,statSync as G2,lstatSync as K2,realpathSync as P$,existsSync as J2,readFileSync as Y2}from"node:fs";import{join as C$,extname as X2,relative as O$,sep as Q2,resolve as eU}from"node:path";function sU(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="*"?t[r+1]==="*"?(e+=".*",r++):e+="[^/]*":n==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(n)?e+="\\"+n:e+=n}return new RegExp(`^${e}$`)}function R$(t,e){if(e.length===0)return!1;let r=t.split("/").pop()??t;for(let n of e){if(!n.includes("/")&&!n.includes("*")){if(r===n||t.split("/").includes(n))return!0;continue}let o=sU(n);if(o.test(t)||o.test(r))return!0}return!1}function iU(t){let e=C$(t,".gitignore");if(!J2(e))return[];try{return Y2(e,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function aU(t,e){return O$(t,e).split(Q2).join("/")}function I$(t,e={}){let{include:r,exclude:n,maxDepth:o=nU,maxFiles:s=oU,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=P$(t)}catch{return{files:[],capped:!1,totalSeen:0}}let d=(i&&i.length>0?i:rU).map(v=>(v.startsWith(".")?v:"."+v).toLowerCase()),l=[...tU,...n??[],...a?iU(u):[]],m=r??[],f=[],p=new Set([u]),h=0,g=!1;function y(v,_){if(g||_>o)return;let b;try{b=W2(v,{withFileTypes:!0})}catch{return}for(let x of b){if(g)return;let P=C$(v,x.name),E=aU(u,P);if(R$(E,l))continue;let R=x.isDirectory(),A=x.isFile(),L=!1;try{L=K2(P).isSymbolicLink()}catch{continue}if(L){if(!c)continue;let F;try{F=P$(P)}catch{continue}let U=O$(u,F);if((U.startsWith("..")||eU(U)===F)&&U.startsWith("..")||p.has(F))continue;p.add(F);try{let te=G2(F);R=te.isDirectory(),A=te.isFile()}catch{continue}}if(R){y(P,_+1);continue}if(!A)continue;let w=X2(P).toLowerCase();if(d.includes(w)&&!(m.length>0&&!R$(E,m))){if(h++,f.length>=s){g=!0;return}f.push(P)}}}return y(u,0),{files:f,capped:g,totalSeen:h}}var tU,rU,nU,oU,A$=S(()=>{"use strict";tU=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],rU=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],nU=5,oU=200});import{readFileSync as N$,readdirSync as F$,unlinkSync as Vy,existsSync as qy,statSync as bl,openSync as D$,fstatSync as M$,closeSync as j$}from"node:fs";import{createHash as z$}from"node:crypto";import{tmpdir as U$}from"node:os";import{join as Wy}from"node:path";function H$(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function cU(t,e="AND"){let r=H$(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!Zs.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function uU(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=H$(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!Zs.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function lU(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function dU(t){return t<=4?1:t<=12?2:3}function Gy(){let t=U$(),e=0;try{let r=F$(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Wy(t,n);for(let a of["","-wal","-shm"])try{Vy(i+a)}catch{}e++}}}catch{}return e}function Ky(t,e){let r=0;try{if(!qy(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=F$(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Wy(t,s),c=bl(i).mtimeMs<n;if(!c){let u=i+"-wal";if(qy(u))try{let d=bl(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Vy(i+u)}catch{}r++}}catch{}}catch{}return r}function pU(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function mU(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let d of i){let l=d+c,m=l+r;for(;u<a.length&&a[u]<l;)u++;u<a.length&&a[u]<=m&&(n++,u++)}}return n}function fU(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var Zs,L$,xl,Z$=S(()=>{"use strict";ln();A$();Zs=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);L$=4096;xl=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#v;#b;#x;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=Qe();this.#t=e??Wy(U$(),`context-mode-${process.pid}.db`),Ho(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),Uo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(sc(s)){oc(this.#t),Ho(this.#t);try{n=new r(this.#t,{timeout:3e4}),Uo(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#H(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Vy(this.#t+e)}catch{}}#H(){this.#e.exec(`
158
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return OI(e,n),n}isExpectedHookEntry(e,r,n){return e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(r.command??"").replace(/\\/g,"/"),o=(En[e]??"").replace(/\\/g,"/"),s=MI[e]??[];return n.includes(o)||s.some(i=>n.includes(i))}rebuildToml(e,r,n){let o=e.split(/\r?\n/),s=[],i=!1;for(let c of o){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(c)){i=!0;continue}if(i){/^\s*\[/.test(c)&&(i=!1,s.push(c));continue}s.push(c)}for(;s.length>0&&s[s.length-1]==="";)s.pop();s.length>0&&s.push("");let a=[...r,...n];if(a.length>0)for(let c of a)s.push(jI(c)),s.push("");return s.join(`
159
+ `)}}});var Lc={};we(Lc,{PLATFORM_ENV_VARS:()=>_s,__resetClaudeCodePluginCacheForTests:()=>HI,__seedClaudeCodePluginCacheMissForTests:()=>UI,detectPlatform:()=>vt,foreignIdentificationEnv:()=>VI,foreignWorkspaceEnv:()=>qI,getAdapter:()=>bs,getEnvVarNames:()=>ZI,getSessionDirSegments:()=>Mi,workspaceEnvVarsFor:()=>Hp});import{existsSync as Rt,readFileSync as zI}from"node:fs";import{resolve as xt}from"node:path";import{homedir as Tv}from"node:os";function FI(){if(uo!==null)return uo!=="miss"&&uo.hasCM;try{let t=xt(Tv(),".claude","plugins","installed_plugins.json"),e=zI(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return uo={hasCM:o},o}catch{return uo="miss",!1}}function HI(){uo=null}function UI(){uo="miss"}function ZI(t){return(_s.get(t)??[]).map(e=>e.name)}function Hp(t){return(_s.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function qI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function VI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function Mi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function vt(t){if(t?.name){let n=Ib[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of _s)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&FI()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=Tv();return Rt(xt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Rt(xt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Rt(xt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Rt(xt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Rt(xt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Rt(xt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Rt(xt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Rt(xt(r,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Rt(xt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Rt(xt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Rt(xt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Rt(xt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Rt(xt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Rt(xt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function bs(t){let e=t??vt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(tp(),ep));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(mx(),px));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(yx(),gx));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(xx(),bx));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(Rx(),Px));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(Dx(),Nx));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(zx(),Lx));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Kx(),Wx));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(Xx(),Jx));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(ov(),nv));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(cv(),av));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(mv(),pv));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(hv(),fv));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(yv(),gv));return new r}case"kimi":{let{KimiAdapter:r}=await Promise.resolve().then(()=>($v(),Ev));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(tp(),ep));return new r}}}var uo,BI,_s,$n=S(()=>{"use strict";Ab();uo=null;BI=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],_s=new Map(BI)});import{resolve as ji}from"node:path";import{homedir as Up}from"node:os";function qe(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?ji(Up(),e.replace(/^~[/\\]?/,"")):ji(e):ji(Up(),".claude")}function WI(t=process.env){return ji(qe(t),"settings.json")}function Bp(t=process.env){let e=[],r=vt();if(r.platform!=="claude-code"){let o=Mi(r.platform);o&&o.length>0&&e.push(ji(Up(),...o,"settings.json"))}let n=WI(t);return e.includes(n)||e.push(n),e}var kn=S(()=>{"use strict";$n()});import{readdirSync as KI,statSync as GI,lstatSync as JI,realpathSync as Pv,existsSync as XI,readFileSync as YI}from"node:fs";import{join as Cv,extname as QI,relative as Ov,sep as eA,resolve as tA}from"node:path";function iA(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="*"?t[r+1]==="*"?(e+=".*",r++):e+="[^/]*":n==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(n)?e+="\\"+n:e+=n}return new RegExp(`^${e}$`)}function Rv(t,e){if(e.length===0)return!1;let r=t.split("/").pop()??t;for(let n of e){if(!n.includes("/")&&!n.includes("*")){if(r===n||t.split("/").includes(n))return!0;continue}let o=iA(n);if(o.test(t)||o.test(r))return!0}return!1}function aA(t){let e=Cv(t,".gitignore");if(!XI(e))return[];try{return YI(e,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function cA(t,e){return Ov(t,e).split(eA).join("/")}function Iv(t,e={}){let{include:r,exclude:n,maxDepth:o=oA,maxFiles:s=sA,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Pv(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:nA).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...rA,...n??[],...a?aA(u):[]],m=r??[],h=[],p=new Set([u]),f=0,g=!1;function y(_,b){if(g||b>o)return;let v;try{v=KI(_,{withFileTypes:!0})}catch{return}for(let E of v){if(g)return;let C=Cv(_,E.name),x=cA(u,C);if(Rv(x,d))continue;let k=E.isDirectory(),P=E.isFile(),N=!1;try{N=JI(C).isSymbolicLink()}catch{continue}if(N){if(!c)continue;let O;try{O=Pv(C)}catch{continue}let F=Ov(u,O);if((F.startsWith("..")||tA(F)===O)&&F.startsWith("..")||p.has(O))continue;p.add(O);try{let K=GI(O);k=K.isDirectory(),P=K.isFile()}catch{continue}}if(k){y(C,b+1);continue}if(!P)continue;let R=QI(C).toLowerCase();if(l.includes(R)&&!(m.length>0&&!Rv(x,m))){if(f++,h.length>=s){g=!0;return}h.push(C)}}}return y(u,0),{files:h,capped:g,totalSeen:f}}var rA,nA,oA,sA,Av=S(()=>{"use strict";rA=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],nA=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],oA=5,sA=200});import{readFileSync as Nv,readdirSync as Fv,unlinkSync as qp,existsSync as Zp,statSync as zc,openSync as Dv,fstatSync as Mv,closeSync as jv}from"node:fs";import{createHash as Lv}from"node:crypto";import{tmpdir as Hv}from"node:os";import{join as Vp}from"node:path";function Uv(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function uA(t,e="AND"){let r=Uv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!xs.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function lA(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=Uv(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!xs.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function dA(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function pA(t){return t<=4?1:t<=12?2:3}function Wp(){let t=Hv(),e=0;try{let r=Fv(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Vp(t,n);for(let a of["","-wal","-shm"])try{qp(i+a)}catch{}e++}}}catch{}return e}function Kp(t,e){let r=0;try{if(!Zp(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=Fv(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Vp(t,s),c=zc(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Zp(u))try{let l=zc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{qp(i+u)}catch{}r++}}catch{}}catch{}return r}function mA(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function fA(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,m=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=m&&(n++,u++)}}return n}function hA(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var xs,zv,vs,Gp=S(()=>{"use strict";bn();Av();xs=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);zv=4096;vs=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#b;#x;#v;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=rt();this.#t=e??Vp(Hv(),`context-mode-${process.pid}.db`),ts(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Sc(s)){vc(this.#t),ts(this.#t);try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#U(),this.#B()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{qp(this.#t+e)}catch{}}#U(){this.#e.exec(`
270
160
  CREATE TABLE IF NOT EXISTS sources (
271
161
  id INTEGER PRIMARY KEY AUTOINCREMENT,
272
162
  label TEXT NOT NULL,
@@ -329,7 +219,7 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
329
219
  timestamp UNINDEXED,
330
220
  tokenize='trigram'
331
221
  );
332
- `))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#Z(){this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#m=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#f=this.#e.prepare(`
222
+ `))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#B(){this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#m=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#f=this.#e.prepare(`
333
223
  SELECT
334
224
  chunks.title,
335
225
  chunks.content,
@@ -337,7 +227,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
337
227
  chunks.timestamp,
338
228
  sources.label,
339
229
  bm25(chunks, 5.0, 1.0) AS rank,
340
- highlight(chunks, 1, char(2), char(3)) AS highlighted
230
+ highlight(chunks, 1, char(2), char(3)) AS highlighted,
231
+ chunks.session_id
341
232
  FROM chunks
342
233
  JOIN sources ON sources.id = chunks.source_id
343
234
  WHERE chunks MATCH ?
@@ -351,7 +242,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
351
242
  chunks.timestamp,
352
243
  sources.label,
353
244
  bm25(chunks, 5.0, 1.0) AS rank,
354
- highlight(chunks, 1, char(2), char(3)) AS highlighted
245
+ highlight(chunks, 1, char(2), char(3)) AS highlighted,
246
+ chunks.session_id
355
247
  FROM chunks
356
248
  JOIN sources ON sources.id = chunks.source_id
357
249
  WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\'
@@ -365,7 +257,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
365
257
  chunks.timestamp,
366
258
  sources.label,
367
259
  bm25(chunks, 5.0, 1.0) AS rank,
368
- highlight(chunks, 1, char(2), char(3)) AS highlighted
260
+ highlight(chunks, 1, char(2), char(3)) AS highlighted,
261
+ chunks.session_id
369
262
  FROM chunks
370
263
  JOIN sources ON sources.id = chunks.source_id
371
264
  WHERE chunks MATCH ? AND sources.label = ?
@@ -379,7 +272,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
379
272
  chunks_trigram.timestamp,
380
273
  sources.label,
381
274
  bm25(chunks_trigram, 5.0, 1.0) AS rank,
382
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted
275
+ highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
276
+ chunks_trigram.session_id
383
277
  FROM chunks_trigram
384
278
  JOIN sources ON sources.id = chunks_trigram.source_id
385
279
  WHERE chunks_trigram MATCH ?
@@ -393,13 +287,14 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
393
287
  chunks_trigram.timestamp,
394
288
  sources.label,
395
289
  bm25(chunks_trigram, 5.0, 1.0) AS rank,
396
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted
290
+ highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
291
+ chunks_trigram.session_id
397
292
  FROM chunks_trigram
398
293
  JOIN sources ON sources.id = chunks_trigram.source_id
399
294
  WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\'
400
295
  ORDER BY rank
401
296
  LIMIT ?
402
- `),this.#v=this.#e.prepare(`
297
+ `),this.#b=this.#e.prepare(`
403
298
  SELECT
404
299
  chunks_trigram.title,
405
300
  chunks_trigram.content,
@@ -407,13 +302,14 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
407
302
  chunks_trigram.timestamp,
408
303
  sources.label,
409
304
  bm25(chunks_trigram, 5.0, 1.0) AS rank,
410
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted
305
+ highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
306
+ chunks_trigram.session_id
411
307
  FROM chunks_trigram
412
308
  JOIN sources ON sources.id = chunks_trigram.source_id
413
309
  WHERE chunks_trigram MATCH ? AND sources.label = ?
414
310
  ORDER BY rank
415
311
  LIMIT ?
416
- `),this.#x=this.#e.prepare(`
312
+ `),this.#v=this.#e.prepare(`
417
313
  SELECT
418
314
  chunks.title,
419
315
  chunks.content,
@@ -421,7 +317,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
421
317
  chunks.timestamp,
422
318
  sources.label,
423
319
  bm25(chunks, 5.0, 1.0) AS rank,
424
- highlight(chunks, 1, char(2), char(3)) AS highlighted
320
+ highlight(chunks, 1, char(2), char(3)) AS highlighted,
321
+ chunks.session_id
425
322
  FROM chunks
426
323
  JOIN sources ON sources.id = chunks.source_id
427
324
  WHERE chunks MATCH ? AND chunks.content_type = ?
@@ -435,7 +332,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
435
332
  chunks.timestamp,
436
333
  sources.label,
437
334
  bm25(chunks, 5.0, 1.0) AS rank,
438
- highlight(chunks, 1, char(2), char(3)) AS highlighted
335
+ highlight(chunks, 1, char(2), char(3)) AS highlighted,
336
+ chunks.session_id
439
337
  FROM chunks
440
338
  JOIN sources ON sources.id = chunks.source_id
441
339
  WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks.content_type = ?
@@ -449,7 +347,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
449
347
  chunks.timestamp,
450
348
  sources.label,
451
349
  bm25(chunks, 5.0, 1.0) AS rank,
452
- highlight(chunks, 1, char(2), char(3)) AS highlighted
350
+ highlight(chunks, 1, char(2), char(3)) AS highlighted,
351
+ chunks.session_id
453
352
  FROM chunks
454
353
  JOIN sources ON sources.id = chunks.source_id
455
354
  WHERE chunks MATCH ? AND sources.label = ? AND chunks.content_type = ?
@@ -463,7 +362,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
463
362
  chunks_trigram.timestamp,
464
363
  sources.label,
465
364
  bm25(chunks_trigram, 5.0, 1.0) AS rank,
466
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted
365
+ highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
366
+ chunks_trigram.session_id
467
367
  FROM chunks_trigram
468
368
  JOIN sources ON sources.id = chunks_trigram.source_id
469
369
  WHERE chunks_trigram MATCH ? AND chunks_trigram.content_type = ?
@@ -477,7 +377,8 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
477
377
  chunks_trigram.timestamp,
478
378
  sources.label,
479
379
  bm25(chunks_trigram, 5.0, 1.0) AS rank,
480
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted
380
+ highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
381
+ chunks_trigram.session_id
481
382
  FROM chunks_trigram
482
383
  JOIN sources ON sources.id = chunks_trigram.source_id
483
384
  WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks_trigram.content_type = ?
@@ -491,13 +392,14 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
491
392
  chunks_trigram.timestamp,
492
393
  sources.label,
493
394
  bm25(chunks_trigram, 5.0, 1.0) AS rank,
494
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted
395
+ highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
396
+ chunks_trigram.session_id
495
397
  FROM chunks_trigram
496
398
  JOIN sources ON sources.id = chunks_trigram.source_id
497
399
  WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
498
400
  ORDER BY rank
499
401
  LIMIT ?
500
- `),this.#b=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#T=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#P=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
402
+ `),this.#x=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#T=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#P=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
501
403
  FROM chunks c
502
404
  JOIN sources s ON s.id = c.source_id
503
405
  WHERE c.source_id = ?
@@ -506,88 +408,214 @@ ${n}`}}}});import{cpus as V2}from"node:os";async function By(t,e){let{concurrenc
506
408
  (SELECT COUNT(*) FROM sources) AS sources,
507
409
  (SELECT COUNT(*) FROM chunks) AS chunks,
508
410
  (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
509
- `),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:o,attribution:s}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let m=D$(n,"r");try{if(!M$(m).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=N$(m,"utf-8")}finally{j$(m)}}let c=o??n??"untitled",u=this.#V(a),d=n??void 0,l=d?z$("sha256").update(a).digest("hex"):void 0;return un(()=>this.#d(u,c,a,d,l,s))}indexDirectory(e){let{path:r,source:n,attribution:o,perFileDeny:s,...i}=e,a=I$(r,i),c=0,u=0,d=0,l=0;for(let m of a.files){if(s&&s(m)){d++;continue}try{let f=n?`${n}:${m}`:m,p=this.index({path:m,source:f,attribution:o});c++,u+=p.totalChunks}catch{l++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:d,failed:l,label:n??r}}indexPlainText(e,r,n=20,o){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,o);let s=this.#W(e,n);return un(()=>this.#d(s.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,o))}indexJSON(e,r,n=L$,o){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,o);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,o)}let i=[];return this.#U(s,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,o):un(()=>this.#d(i,r,e,void 0,void 0,o))}#d(e,r,n,o,s,i){let a=e.filter(m=>m.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",l=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let h=this.#s.run(r,o??null,s??null);return Number(h.lastInsertRowid)}let m=this.#o.run(r,e.length,a,o??null,s??null),f=Number(m.lastInsertRowid),p=new Date().toISOString();for(let h of e){let g=h.hasCode?"code":"prose";this.#a.run(h.title,h.content,f,g,null,c,u,p),this.#c.run(h.title,h.content,f,g,null,c,u,p)}return f})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:l,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,r=3,n,o="AND",s,i="like"){let a=cU(e,o),c,u;return n&&s?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):s?(c=this.#x,u=[a,s,r]):(c=this.#f,u=[a,r]),un(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=uU(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#v:this.#_,u=[a,this.#p(n,i),r]):s?(c=this.#w,u=[a,s,r]):(c=this.#y,u=[a,r]),un(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=dU(r.length),o=this.#b.all(r.length-n,r.length+n),s=null,i=n+1,a=!1;for(let{word:u}of o){if(u===r){a=!0;break}let d=lU(r,u);d<i&&(i=d,s=u)}let c=a?null:i<=n?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#z(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),d=new Map,l=m=>`${m.source}::${m.title}`;for(let[m,f]of c.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}for(let[m,f]of u.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}return Array.from(d.values()).sort((m,f)=>f.score-m.score).slice(0,r).map(({result:m,score:f})=>({...m,rank:-f}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=n.filter(i=>!Zs.has(i)),s=o.length>0?o:n;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/s.length):0,l=0,m=0;if(s.length>=2){let f=i.content.toLowerCase(),p=s.map(h=>pU(f,h));if(!p.some(h=>h.length===0)){l=1/(1+fU(p)/Math.max(f.length,1));let g=mU(p,s);m=.5*Math.min(1,g/4)}}return{result:i,boost:d+l+m}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,o,s="like"){this.#B();let i=this.#z(e,r,n,o,s);if(i.length>0)return this.#L(i,e).map(m=>({...m,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(l=>l.length>=3&&!Zs.has(l)),c=a.join(" "),d=a.map(l=>this.fuzzyCorrect(l)??l).join(" ");if(d!==c){let l=this.#z(d,r,n,o,s);if(l.length>0)return this.#L(l,d).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#B(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!qy(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=bl(r.file_path).mtime,o=new Date(r.indexed_at+"Z");if(n<=o)continue;let s=D$(r.file_path,"r"),i;try{if(!M$(s).isFile())continue;i=N$(s,"utf-8")}finally{j$(s)}if(z$("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#T.all()}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#R.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let d of this.#C.iterate(e)){let l=new Set(d.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(m=>m.length>=3&&!Zs.has(m)));for(let m of l)a.set(m,(a.get(m)??0)+1)}return Array.from(a.entries()).filter(([,d])=>d>=s&&d<=i).map(([d,l])=>{let m=Math.log(o/l),f=Math.min(d.length/20,.5),p=/[_]/.test(d),h=d.length>=12,g=p?1.5:h?.8:0;return{word:d,score:m+f+g}}).sort((d,l)=>l.score-d.score).slice(0,r).map(d=>d.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#A.run(o),this.#N.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return bl(this.#t).size}catch{return 0}}#F(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#F(),Zo(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!Zs.has(s)),n=[...new Set(r)],o=0;this.#e.transaction(()=>{for(let s of n){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#V(e,r=L$){let n=[],o=e.split(`
510
- `),s=[],i=[],a="",c=()=>{let d=i.join(`
511
- `).trim();if(d.length===0)return;let l=this.#Y(s,a),m=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(d)<=r){n.push({title:l,content:d,hasCode:m}),i=[];return}let f=d.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let y=p.join(`
411
+ `),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:o,attribution:s}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let m=Dv(n,"r");try{if(!Mv(m).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=Nv(m,"utf-8")}finally{jv(m)}}let c=o??n??"untitled",u=this.#W(a),l=n??void 0,d=l?Lv("sha256").update(a).digest("hex"):void 0;return _n(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:r,source:n,attribution:o,perFileDeny:s,...i}=e,a=Iv(r,i),c=0,u=0,l=0,d=0;for(let m of a.files){if(s&&s(m)){l++;continue}try{let h=n?`${n}:${m}`:m,p=this.index({path:m,source:h,attribution:o});c++,u+=p.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:n??r}}indexPlainText(e,r,n=20,o){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,o);let s=this.#K(e,n);return _n(()=>this.#d(s.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,o))}indexJSON(e,r,n=zv,o){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,o);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,o)}let i=[];return this.#H(s,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,o):_n(()=>this.#d(i,r,e,void 0,void 0,o))}#d(e,r,n,o,s,i){let a=e.filter(m=>m.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let f=this.#s.run(r,o??null,s??null);return Number(f.lastInsertRowid)}let m=this.#o.run(r,e.length,a,o??null,s??null),h=Number(m.lastInsertRowid),p=new Date().toISOString();for(let f of e){let g=f.hasCode?"code":"prose";this.#a.run(f.title,f.content,h,g,null,c,u,p),this.#c.run(f.title,f.content,h,g,null,c,u,p)}return h})();return n&&this.#V(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:d,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0,sessionId:r.session_id??""}))}#p(e,r){return r==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,r=3,n,o="AND",s,i="like"){let a=uA(e,o),c,u;return n&&s?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):s?(c=this.#v,u=[a,s,r]):(c=this.#f,u=[a,r]),_n(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=lA(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#b:this.#_,u=[a,this.#p(n,i),r]):s?(c=this.#w,u=[a,s,r]):(c=this.#y,u=[a,r]),_n(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=pA(r.length),o=this.#x.all(r.length-n,r.length+n),s=null,i=n+1,a=!1;for(let{word:u}of o){if(u===r){a=!0;break}let l=dA(r,u);l<i&&(i=l,s=u)}let c=a?null:i<=n?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#L(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),l=new Map,d=m=>`${m.source}::${m.title}`;for(let[m,h]of c.entries()){let p=d(h),f=l.get(p);f?f.score+=1/(60+m+1):l.set(p,{result:h,score:1/(60+m+1)})}for(let[m,h]of u.entries()){let p=d(h),f=l.get(p);f?f.score+=1/(60+m+1):l.set(p,{result:h,score:1/(60+m+1)})}return Array.from(l.values()).sort((m,h)=>h.score-m.score).slice(0,r).map(({result:m,score:h})=>({...m,rank:-h}))}#z(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=n.filter(i=>!xs.has(i)),s=o.length>0?o:n;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(h=>a.includes(h)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,m=0;if(s.length>=2){let h=i.content.toLowerCase(),p=s.map(f=>mA(h,f));if(!p.some(f=>f.length===0)){d=1/(1+hA(p)/Math.max(h.length,1));let g=fA(p,s);m=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+m}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,o,s="like",i){this.#q();let a=i?Math.max(r*8,40):r,c=this.#Z(i),u=this.#L(e,a,n,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#z(l.slice(0,r),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(f=>f.length>=3&&!xs.has(f)),m=d.join(" "),p=d.map(f=>this.fuzzyCorrect(f)??f).join(" ");if(p!==m){let f=this.#L(p,a,n,o,s),g=c?f.filter(c):f;if(g.length>0)return this.#z(g.slice(0,r),p).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#Z(e){return e?r=>{let n=r.sessionId??"";return n===""||e.has(n)}:null}lastRefreshCount=0;#q(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!Zp(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=zc(r.file_path).mtime,o=new Date(r.indexed_at+"Z");if(n<=o)continue;let s=Dv(r.file_path,"r"),i;try{if(!Mv(s).isFile())continue;i=Nv(s,"utf-8")}finally{jv(s)}if(Lv("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#T.all()}getIndexState(){let e=this.#e.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS total_chunks, COUNT(*) AS total_sources, MAX(indexed_at) AS last_indexed_at FROM sources").get();return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#R.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#C.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(m=>m.length>=3&&!xs.has(m)));for(let m of d)a.set(m,(a.get(m)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let m=Math.log(o/d),h=Math.min(l.length/20,.5),p=/[_]/.test(l),f=l.length>=12,g=p?1.5:f?.8:0;return{word:l,score:m+h+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#A.run(o),this.#N.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return zc(this.#t).size}catch{return 0}}#F(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#F(),rs(this.#e)}#V(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!xs.has(s)),n=[...new Set(r)],o=0;this.#e.transaction(()=>{for(let s of n){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#W(e,r=zv){let n=[],o=e.split(`
412
+ `),s=[],i=[],a="",c=()=>{let l=i.join(`
413
+ `).trim();if(l.length===0)return;let d=this.#Y(s,a),m=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:m}),i=[];return}let h=l.split(/\n\n+/),p=[],f=1,g=()=>{if(p.length===0)return;let y=p.join(`
414
+
415
+ `).trim();if(y.length===0)return;let _=h.length>1?`${d} (${f})`:d;f++,n.push({title:_,content:y,hasCode:y.includes("```")}),p=[]};for(let y of h){p.push(y);let _=p.join(`
416
+
417
+ `);Buffer.byteLength(_)>r&&p.length>1&&(p.pop(),g(),p=[y])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let h=d[1].length,p=d[2].trim();for(;s.length>0&&s[s.length-1].level>=h;)s.pop();s.push({level:h,text:p}),a=p,i.push(l),u++;continue}let m=l.match(/^(`{3,})(.*)?$/);if(m){let h=m[1],p=[l];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(h)&&o[u].trim()===h){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),n}#K(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let l=c.trim();return{title:l.split(`
418
+ `)[0].slice(0,80)||`Section ${u+1}`,content:l}}).filter(c=>c.content.length>0);let o=e.split(`
419
+ `);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let l=c+1,d=Math.min(c+u.length,o.length),m=u[0]?.trim().slice(0,80);s.push({title:m||`Lines ${l}-${d}`,content:u.join(`
420
+ `)})}return s}#H(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#H(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#X(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#J(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#X(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#J(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});import{readFileSync as Zv,realpathSync as gA}from"node:fs";import{resolve as Li}from"node:path";function qv(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function yA(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function _A(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Bv(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function bA(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=_A(o),a=Bv(s);r=`^${i}(\\s${a})?$`}else r=`^${Bv(t)}$`;return new RegExp(r,e?"i":"")}function xA(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function vA(t,e,r=!1){for(let n of e){let o=qv(n);if(o&&bA(o,r).test(t))return n}return null}function SA(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function Jp(t){let e;try{e=Zv(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&qv(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function Xp(t,e){let r=[];if(t){let o=Li(t,".claude","settings.local.json"),s=Jp(o);s&&r.push(s);let i=Li(t,".claude","settings.json"),a=Jp(i);a&&r.push(a)}let n=e!==void 0?[e]:Bp();for(let o of n){let s=Jp(o);s&&r.push(s)}return r}function lo(t,e,r){let n=[],o=i=>{let a;try{a=Zv(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let l=[];for(let d of u){if(typeof d!="string")continue;let m=yA(d);m&&m.tool===t&&l.push(m.glob)}return l};if(e){let i=o(Li(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=o(Li(e,".claude","settings.json"));a!==null&&n.push(a)}let s=r!==void 0?[r]:Bp();for(let i of s){let a=o(i);a!==null&&n.push(a)}return n}function Yp(t,e,r=process.platform==="win32"){let n=SA(t);for(let o of n)for(let s of e){let i=vA(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function po(t,e,r=process.platform==="win32",n){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),n){let i=Li(n,t);s.add(o(i));try{s.add(o(gA(i)))}catch{}}for(let i of e)for(let a of i){let c=xA(o(a),r);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function wA(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function Vv(t,e){let r=kA[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...wA(t)),n}var kA,Qp=S(()=>{"use strict";kn();kA={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});var Gv={};we(Gv,{healClaudeJsonMcpArgs:()=>zA,healInstalledPlugins:()=>MA,healMcpJsonArgs:()=>LA,healPluginJsonMcpServers:()=>Fc,healSettingsEnabledPlugins:()=>jA,sweepStaleMcpJson:()=>Hc});import{existsSync as Qr,readFileSync as Ss,writeFileSync as Fi,readdirSync as AA,unlinkSync as NA,statSync as DA}from"node:fs";import{resolve as St,sep as mo}from"node:path";function MA({registryPath:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!Qr(t))return{healed:[],skipped:"no-registry"};let n;try{n=Ss(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}if(!o||typeof o!="object")return{healed:[],error:"bad-shape"};let s=o.plugins&&o.plugins[r]||[];if(!Array.isArray(s)||s.length===0)return{healed:[],skipped:"no-entry"};let i=[],a=null;for(let c of s){if(!c||typeof c!="object")continue;let u=c.installPath;if(!u||typeof u!="string")continue;let l=St(u),d=St(e)+mo;if(!l.startsWith(d))continue;let m=St(u,".claude-plugin","plugin.json");if(!Qr(m))continue;let h=null;try{let p=JSON.parse(Ss(m,"utf-8"));p&&typeof p.version=="string"&&p.version&&(h=p.version)}catch{continue}h&&(a=h,c.version!==h&&(c.version=h,i.includes("entry-version")||i.push("entry-version")))}if(a){(!o.enabledPlugins||typeof o.enabledPlugins!="object"||Array.isArray(o.enabledPlugins))&&(o.enabledPlugins={});let c=o.enabledPlugins[r];(c==null||c===!1||c==="")&&(o.enabledPlugins[r]=!0,i.push("enabled-plugins"))}if(i.length>0)try{Fi(t,JSON.stringify(o,null,2)+`
421
+ `,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function jA({settingsPath:t,pluginKey:e}){if(!t||!Qr(t))return{healed:[],skipped:"no-settings"};let r;try{r=Ss(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let n;try{n=JSON.parse(r)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!n.enabledPlugins||typeof n.enabledPlugins!="object"||Array.isArray(n.enabledPlugins))&&(n.enabledPlugins={});let s=n.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(n.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{Fi(t,JSON.stringify(n,null,2)+`
422
+ `,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function Fc({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=St(t),o=St(e)+mo;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=St(t,".claude-plugin","plugin.json");if(!Qr(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=Ss(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],m=l.args,h=m.map(f=>typeof f!="string"||f===zi?f:/[/\\]start\.mjs$/.test(f)?zi:f);if(h.some((f,g)=>f!==m[g])){l.args=h,d.push("plugin-json-args");try{Fi(s,JSON.stringify(a,null,2)+`
423
+ `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function LA({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=St(t),o=St(e)+mo;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=St(t,".mcp.json");if(!Qr(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=Ss(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],m=l.args,h=m.map(f=>typeof f!="string"||f===zi?f:f==="./start.mjs"||f==="start.mjs"||/[/\\]start\.mjs$/.test(f)?zi:f);if(h.some((f,g)=>f!==m[g])){l.args=h,d.push("mcp-json-args");try{Fi(s,JSON.stringify(a,null,2)+`
424
+ `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function zA({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!Qr(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=Ss(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(n)}catch(l){return{healed:[],error:`parse-failed: ${l&&l.message||l}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=St(r),c=a+mo,u=!1;for(let l of Object.values(s))if(!(!l||typeof l!="object"||!Array.isArray(l.args)))for(let d=0;d<l.args.length;d++){let m=l.args[d];if(typeof m!="string")continue;let h=m.replace(/\\/g,"/");if(!h.startsWith(i+"/"))continue;let p=h.slice(i.length+1),f=p.indexOf("/");if(f<0)continue;let g=p.slice(f+1),y=St(r,g);y!==a&&!(y+mo).startsWith(c)||y!==m&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{Fi(t,JSON.stringify(o,null,2),"utf-8")}catch(l){return{healed:[],error:`write-failed: ${l&&l.message||l}`}}return{healed:["claude-json-mcp-args"]}}function Hc({pluginCacheRoot:t,pluginKey:e}){let r=[];if(!t||!e)return{removed:r,skipped:"missing-args"};let n=St(t);if(!Qr(n))return{removed:r,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:r,skipped:"bad-plugin-key"};let i=St(n,o,s),a=n+mo;if(!i.startsWith(a))return{removed:r,skipped:"outside-cache-root"};if(!Qr(i))return{removed:r,skipped:"no-plugin-dir"};let c=[];try{c=AA(i)}catch{return{removed:r,skipped:"readdir-failed"}}for(let u of c){let l=St(i,u);if(!l.startsWith(i+mo))continue;try{if(!DA(l).isDirectory())continue}catch{continue}let d=St(l,".mcp.json");if(Qr(d))try{NA(d),r.push(d)}catch{}}return{removed:r}}var zi,em=S(()=>{"use strict";zi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,tm,z,Nr,Hi=S(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(tm||(tm={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Nr=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}}});var A,UA,Ct,Uc=S(()=>{Hi();A=ce.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),UA=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ct=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ct.create=t=>new Ct(t)});var BA,en,rm=S(()=>{Uc();Hi();BA=(t,e)=>{let r;switch(t.code){case A.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case A.invalid_union:r="Invalid input";break;case A.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case A.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:r="Invalid function arguments";break;case A.invalid_return_type:r="Invalid function return type";break;case A.invalid_date:r="Invalid date";break;case A.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case A.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case A.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case A.custom:r="Invalid input";break;case A.invalid_intersection_types:r="Intersection results could not be merged";break;case A.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},en=BA});function ZA(t){Xv=t}function ks(){return Xv}var Xv,Bc=S(()=>{rm();Xv=en});function j(t,e){let r=ks(),n=Ui({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===en?void 0:en].filter(o=>!!o)});t.common.issues.push(n)}var Ui,qA,st,J,fo,mt,Zc,qc,Tn,ws,nm=S(()=>{Bc();rm();Ui=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},qA=[];st=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return J;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return J;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},J=Object.freeze({status:"aborted"}),fo=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),Zc=t=>t.status==="aborted",qc=t=>t.status==="dirty",Tn=t=>t.status==="valid",ws=t=>typeof Promise<"u"&&t instanceof Promise});var Yv=S(()=>{});var U,Qv=S(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function nS(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function cN(t){return new RegExp(`^${nS(t)}$`)}function oS(t){let e=`${rS}T${nS(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function uN(t,e){return!!((e==="v4"||!e)&&tN.test(t)||(e==="v6"||!e)&&nN.test(t))}function lN(t,e){if(!XA.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function dN(t,e){return!!((e==="v4"||!e)&&rN.test(t)||(e==="v6"||!e)&&oN.test(t))}function pN(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Es(t){if(t instanceof It){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ot.create(Es(n))}return new It({...t._def,shape:()=>e})}else return t instanceof nn?new nn({...t._def,type:Es(t.element)}):t instanceof Ot?Ot.create(Es(t.unwrap())):t instanceof Mr?Mr.create(Es(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>Es(e))):t}function sm(t,e){let r=Nr(t),n=Nr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=ce.objectKeys(e),s=ce.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=sm(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=sm(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function sS(t,e){return new Eo({values:t,typeName:D.ZodEnum,...te(e)})}function tS(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function iS(t,e={},r){return t?Rn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=tS(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=tS(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Rn.create()}var tr,eS,ne,VA,WA,KA,GA,JA,XA,YA,QA,eN,om,tN,rN,nN,oN,sN,iN,rS,aN,Pn,ho,go,yo,_o,$s,bo,xo,Rn,rn,hr,Ts,nn,It,vo,tn,Vc,So,Dr,Wc,Ps,Rs,Kc,ko,wo,Eo,$o,Cn,rr,Ot,Mr,To,Po,Cs,mN,Bi,Zi,Ro,fN,D,hN,aS,cS,gN,yN,uS,_N,bN,xN,vN,SN,kN,wN,EN,$N,im,TN,PN,RN,CN,ON,IN,AN,NN,DN,MN,jN,LN,zN,FN,HN,UN,BN,ZN,qN,VN,WN,KN,GN,JN,lS=S(()=>{Uc();Bc();Qv();nm();Hi();tr=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},eS=(t,e)=>{if(Tn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ct(t.common.issues);return this._error=r,this._error}}};ne=class{get description(){return this._def.description}_getType(e){return Nr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new st,ctx:{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ws(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return eS(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Tn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Tn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ws(o)?o:Promise.resolve(o));return eS(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:A.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new rr({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ot.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nn.create(this)}promise(){return Cn.create(this,this._def)}or(e){return vo.create([this,e],this._def)}and(e){return So.create(this,e,this._def)}transform(e){return new rr({...te(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new To({...te(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new Bi({typeName:D.ZodBranded,type:this,...te(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Po({...te(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Zi.create(this,e)}readonly(){return Ro.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},VA=/^c[^\s-]{8,}$/i,WA=/^[0-9a-z]+$/,KA=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GA=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,JA=/^[a-z0-9_-]{21}$/i,XA=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,YA=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,QA=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",tN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,nN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,oN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,iN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rS="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aN=new RegExp(`^${rS}$`);Pn=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.string,received:s.parsedType}),J}let n=new st,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?j(o,{code:A.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&j(o,{code:A.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")QA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"email",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")om||(om=new RegExp(eN,"u")),om.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"emoji",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")GA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"uuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")JA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"nanoid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")VA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")WA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid2",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")KA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ulid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),j(o,{validation:"url",code:A.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"regex",code:A.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?oS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?aN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?cN(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?YA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"duration",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?uN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ip",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?lN(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"jwt",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?dN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cidr",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?sN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?iN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64url",code:A.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:A.invalid_string,...U.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...U.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...U.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...U.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...U.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...U.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...U.errToObj(r)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Pn.create=t=>new Pn({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...te(t)});ho=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.number,received:s.parsedType}),J}let n,o=new st;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?pN(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,U.toString(r))}gt(e,r){return this.setLimit("min",e,!1,U.toString(r))}lte(e,r){return this.setLimit("max",e,!0,U.toString(r))}lt(e,r){return this.setLimit("max",e,!1,U.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:U.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};ho.create=t=>new ho({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...te(t)});go=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new st;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,U.toString(r))}gt(e,r){return this.setLimit("min",e,!1,U.toString(r))}lte(e,r){return this.setLimit("max",e,!0,U.toString(r))}lt(e,r){return this.setLimit("max",e,!1,U.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:U.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};go.create=t=>new go({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...te(t)});yo=class extends ne{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.boolean,received:n.parsedType}),J}return mt(e.data)}};yo.create=t=>new yo({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...te(t)});_o=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_date}),J}let n=new st,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:U.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};_o.create=t=>new _o({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...te(t)});$s=class extends ne{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.symbol,received:n.parsedType}),J}return mt(e.data)}};$s.create=t=>new $s({typeName:D.ZodSymbol,...te(t)});bo=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.undefined,received:n.parsedType}),J}return mt(e.data)}};bo.create=t=>new bo({typeName:D.ZodUndefined,...te(t)});xo=class extends ne{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.null,received:n.parsedType}),J}return mt(e.data)}};xo.create=t=>new xo({typeName:D.ZodNull,...te(t)});Rn=class extends ne{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};Rn.create=t=>new Rn({typeName:D.ZodAny,...te(t)});rn=class extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};rn.create=t=>new rn({typeName:D.ZodUnknown,...te(t)});hr=class extends ne{_parse(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.never,received:r.parsedType}),J}};hr.create=t=>new hr({typeName:D.ZodNever,...te(t)});Ts=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.void,received:n.parsedType}),J}return mt(e.data)}};Ts.create=t=>new Ts({typeName:D.ZodVoid,...te(t)});nn=class t extends ne{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return j(r,{code:A.invalid_type,expected:z.array,received:r.parsedType}),J;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(j(r,{code:i?A.too_big:A.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(j(r,{code:A.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(j(r,{code:A.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new tr(r,i,r.path,a)))).then(i=>st.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new tr(r,i,r.path,a)));return st.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:U.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:U.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:U.toString(r)}})}nonempty(e){return this.min(1,e)}};nn.create=(t,e)=>new nn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...te(e)});It=class t extends ne{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return j(u,{code:A.invalid_type,expected:z.object,received:u.parsedType}),J}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof hr&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new tr(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof hr){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(j(o,{code:A.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new tr(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,m=await l.value;u.push({key:d,value:m,alwaysSet:l.alwaysSet})}return u}).then(u=>st.mergeObjectSync(n,u)):st.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:U.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ce.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Es(this)}partial(e){let r={};for(let n of ce.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ot;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return sS(ce.objectKeys(this.shape))}};It.create=(t,e)=>new It({shape:()=>t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.strictCreate=(t,e)=>new It({shape:()=>t,unknownKeys:"strict",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.lazycreate=(t,e)=>new It({shape:t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});vo=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ct(a.ctx.common.issues));return j(r,{code:A.invalid_union,unionErrors:i}),J}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ct(c));return j(r,{code:A.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};vo.create=(t,e)=>new vo({options:t,typeName:D.ZodUnion,...te(e)});tn=t=>t instanceof ko?tn(t.schema):t instanceof rr?tn(t.innerType()):t instanceof wo?[t.value]:t instanceof Eo?t.options:t instanceof $o?ce.objectValues(t.enum):t instanceof To?tn(t._def.innerType):t instanceof bo?[void 0]:t instanceof xo?[null]:t instanceof Ot?[void 0,...tn(t.unwrap())]:t instanceof Mr?[null,...tn(t.unwrap())]:t instanceof Bi||t instanceof Ro?tn(t.unwrap()):t instanceof Po?tn(t._def.innerType):[],Vc=class t extends ne{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return j(r,{code:A.invalid_type,expected:z.object,received:r.parsedType}),J;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(j(r,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=tn(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...te(n)})}};So=class extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Zc(s)||Zc(i))return J;let a=sm(s.value,i.value);return a.valid?((qc(s)||qc(i))&&r.dirty(),{status:r.value,value:a.data}):(j(n,{code:A.invalid_intersection_types}),J)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};So.create=(t,e,r)=>new So({left:t,right:e,typeName:D.ZodIntersection,...te(r)});Dr=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return j(n,{code:A.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return j(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new tr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>st.mergeArray(r,i)):st.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:D.ZodTuple,rest:null,...te(e)})};Wc=class t extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return j(n,{code:A.invalid_type,expected:z.object,received:n.parsedType}),J;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new tr(n,a,n.path,a)),value:i._parse(new tr(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?st.mergeObjectAsync(r,o):st.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ne?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...te(n)}):new t({keyType:Pn.create(),valueType:e,typeName:D.ZodRecord,...te(r)})}},Ps=class extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return j(n,{code:A.invalid_type,expected:z.map,received:n.parsedType}),J;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new tr(n,a,n.path,[u,"key"])),value:s._parse(new tr(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return J;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return J;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Ps.create=(t,e,r)=>new Ps({valueType:e,keyType:t,typeName:D.ZodMap,...te(r)});Rs=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return j(n,{code:A.invalid_type,expected:z.set,received:n.parsedType}),J;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(j(n,{code:A.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(j(n,{code:A.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return J;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new tr(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:U.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:U.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Rs.create=(t,e)=>new Rs({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...te(e)});Kc=class t extends ne{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return j(r,{code:A.invalid_type,expected:z.function,received:r.parsedType}),J;function n(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),en].filter(u=>!!u),issueData:{code:A.invalid_arguments,argumentsError:c}})}function o(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),en].filter(u=>!!u),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Cn){let a=this;return mt(async function(...c){let u=new Ct([]),l=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(o(d,h)),u})})}else{let a=this;return mt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ct([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ct([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Dr.create(e).rest(rn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Dr.create([]).rest(rn.create()),returns:r||rn.create(),typeName:D.ZodFunction,...te(n)})}},ko=class extends ne{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ko.create=(t,e)=>new ko({getter:t,typeName:D.ZodLazy,...te(e)});wo=class extends ne{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return j(r,{received:r.data,code:A.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};wo.create=(t,e)=>new wo({value:t,typeName:D.ZodLiteral,...te(e)});Eo=class t extends ne{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{expected:ce.joinValues(n),received:r.parsedType,code:A.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{received:r.data,code:A.invalid_enum_value,options:n}),J}return mt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Eo.create=sS;$o=class extends ne{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=ce.objectValues(r);return j(n,{expected:ce.joinValues(o),received:n.parsedType,code:A.invalid_type}),J}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(r);return j(n,{received:n.data,code:A.invalid_enum_value,options:o}),J}return mt(e.data)}get enum(){return this._def.values}};$o.create=(t,e)=>new $o({values:t,typeName:D.ZodNativeEnum,...te(e)});Cn=class extends ne{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return j(r,{code:A.invalid_type,expected:z.promise,received:r.parsedType}),J;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return mt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Cn.create=(t,e)=>new Cn({type:t,typeName:D.ZodPromise,...te(e)});rr=class extends ne{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{j(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return J;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?fo(c.value):r.value==="dirty"?fo(c.value):c});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"?fo(a.value):r.value==="dirty"?fo(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Tn(i))return J;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Tn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):J);ce.assertNever(o)}};rr.create=(t,e,r)=>new rr({schema:t,typeName:D.ZodEffects,effect:e,...te(r)});rr.createWithPreprocess=(t,e,r)=>new rr({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...te(r)});Ot=class extends ne{_parse(e){return this._getType(e)===z.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:D.ZodOptional,...te(e)});Mr=class extends ne{_parse(e){return this._getType(e)===z.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:D.ZodNullable,...te(e)});To=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};To.create=(t,e)=>new To({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Po=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ws(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Po.create=(t,e)=>new Po({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Cs=class extends ne{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Cs.create=t=>new Cs({typeName:D.ZodNaN,...te(t)});mN=Symbol("zod_brand"),Bi=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Zi=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?(r.dirty(),fo(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?J:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:D.ZodPipeline})}},Ro=class extends ne{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Tn(o)&&(o.value=Object.freeze(o.value)),o);return ws(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:D.ZodReadonly,...te(e)});fN={object:It.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));hN=(t,e={message:`Input not instance of ${t.name}`})=>iS(r=>r instanceof t,e),aS=Pn.create,cS=ho.create,gN=Cs.create,yN=go.create,uS=yo.create,_N=_o.create,bN=$s.create,xN=bo.create,vN=xo.create,SN=Rn.create,kN=rn.create,wN=hr.create,EN=Ts.create,$N=nn.create,im=It.create,TN=It.strictCreate,PN=vo.create,RN=Vc.create,CN=So.create,ON=Dr.create,IN=Wc.create,AN=Ps.create,NN=Rs.create,DN=Kc.create,MN=ko.create,jN=wo.create,LN=Eo.create,zN=$o.create,FN=Cn.create,HN=rr.create,UN=Ot.create,BN=Mr.create,ZN=rr.createWithPreprocess,qN=Zi.create,VN=()=>aS().optional(),WN=()=>cS().optional(),KN=()=>uS().optional(),GN={string:(t=>Pn.create({...t,coerce:!0})),number:(t=>ho.create({...t,coerce:!0})),boolean:(t=>yo.create({...t,coerce:!0})),bigint:(t=>go.create({...t,coerce:!0})),date:(t=>_o.create({...t,coerce:!0}))},JN=J});var M={};we(M,{BRAND:()=>mN,DIRTY:()=>fo,EMPTY_PATH:()=>qA,INVALID:()=>J,NEVER:()=>JN,OK:()=>mt,ParseStatus:()=>st,Schema:()=>ne,ZodAny:()=>Rn,ZodArray:()=>nn,ZodBigInt:()=>go,ZodBoolean:()=>yo,ZodBranded:()=>Bi,ZodCatch:()=>Po,ZodDate:()=>_o,ZodDefault:()=>To,ZodDiscriminatedUnion:()=>Vc,ZodEffects:()=>rr,ZodEnum:()=>Eo,ZodError:()=>Ct,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Kc,ZodIntersection:()=>So,ZodIssueCode:()=>A,ZodLazy:()=>ko,ZodLiteral:()=>wo,ZodMap:()=>Ps,ZodNaN:()=>Cs,ZodNativeEnum:()=>$o,ZodNever:()=>hr,ZodNull:()=>xo,ZodNullable:()=>Mr,ZodNumber:()=>ho,ZodObject:()=>It,ZodOptional:()=>Ot,ZodParsedType:()=>z,ZodPipeline:()=>Zi,ZodPromise:()=>Cn,ZodReadonly:()=>Ro,ZodRecord:()=>Wc,ZodSchema:()=>ne,ZodSet:()=>Rs,ZodString:()=>Pn,ZodSymbol:()=>$s,ZodTransformer:()=>rr,ZodTuple:()=>Dr,ZodType:()=>ne,ZodUndefined:()=>bo,ZodUnion:()=>vo,ZodUnknown:()=>rn,ZodVoid:()=>Ts,addIssueToContext:()=>j,any:()=>SN,array:()=>$N,bigint:()=>yN,boolean:()=>uS,coerce:()=>GN,custom:()=>iS,date:()=>_N,datetimeRegex:()=>oS,defaultErrorMap:()=>en,discriminatedUnion:()=>RN,effect:()=>HN,enum:()=>LN,function:()=>DN,getErrorMap:()=>ks,getParsedType:()=>Nr,instanceof:()=>hN,intersection:()=>CN,isAborted:()=>Zc,isAsync:()=>ws,isDirty:()=>qc,isValid:()=>Tn,late:()=>fN,lazy:()=>MN,literal:()=>jN,makeIssue:()=>Ui,map:()=>AN,nan:()=>gN,nativeEnum:()=>zN,never:()=>wN,null:()=>vN,nullable:()=>BN,number:()=>cS,object:()=>im,objectUtil:()=>tm,oboolean:()=>KN,onumber:()=>WN,optional:()=>UN,ostring:()=>VN,pipeline:()=>qN,preprocess:()=>ZN,promise:()=>FN,quotelessJson:()=>UA,record:()=>IN,set:()=>NN,setErrorMap:()=>ZA,strictObject:()=>TN,string:()=>aS,symbol:()=>bN,transformer:()=>HN,tuple:()=>ON,undefined:()=>xN,union:()=>PN,unknown:()=>kN,util:()=>ce,void:()=>EN});var Gc=S(()=>{Bc();nm();Yv();Hi();lS();Uc()});var qi=S(()=>{Gc()});function T(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Ft(t){return t&&Object.assign(Jc,t),Jc}var YN,on,Jc,Os=S(()=>{YN=Object.freeze({status:"aborted"});on=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jc={}});var ue={};we(ue,{BIGINT_FORMAT_RANGES:()=>pS,Class:()=>cm,NUMBER_FORMAT_RANGES:()=>hm,aborted:()=>Oo,allowsEval:()=>pm,assert:()=>nD,assertEqual:()=>QN,assertIs:()=>tD,assertNever:()=>rD,assertNotEqual:()=>eD,assignProp:()=>dm,cached:()=>Ki,captureStackTrace:()=>Yc,cleanEnum:()=>gD,cleanRegex:()=>Ji,clone:()=>Ht,createTransparentProxy:()=>uD,defineLazy:()=>Te,esc:()=>Co,escapeRegex:()=>On,extend:()=>pD,finalizeIssue:()=>gr,floatSafeRemainder:()=>lm,getElementAtPath:()=>oD,getEnumValues:()=>Wi,getLengthableOrigin:()=>Xi,getParsedType:()=>cD,getSizableOrigin:()=>mS,isObject:()=>Is,isPlainObject:()=>As,issue:()=>gm,joinValues:()=>Xc,jsonStringifyReplacer:()=>um,merge:()=>mD,normalizeParams:()=>X,nullish:()=>Gi,numKeys:()=>aD,omit:()=>dD,optionalKeys:()=>fm,partial:()=>fD,pick:()=>lD,prefixIssues:()=>jr,primitiveTypes:()=>dS,promiseAllObject:()=>sD,propertyKeyTypes:()=>mm,randomString:()=>iD,required:()=>hD,stringifyPrimitive:()=>Qc,unwrapMessage:()=>Vi});function QN(t){return t}function eD(t){return t}function tD(t){}function rD(t){throw new Error}function nD(t){}function Wi(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Xc(t,e="|"){return t.map(r=>Qc(r)).join(e)}function um(t,e){return typeof e=="bigint"?e.toString():e}function Ki(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gi(t){return t==null}function Ji(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function lm(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Te(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function dm(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function oD(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function sD(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function iD(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Co(t){return JSON.stringify(t)}function Is(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function As(t){if(Is(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Is(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function aD(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function On(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function X(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function uD(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Qc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function fm(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function lD(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Ht(t,{...t._zod.def,shape:r,checks:[]})}function dD(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Ht(t,{...t._zod.def,shape:r,checks:[]})}function pD(t,e){if(!As(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return dm(this,"shape",n),n},checks:[]};return Ht(t,r)}function mD(t,e){return Ht(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return dm(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function fD(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Ht(e,{...e._zod.def,shape:o,checks:[]})}function hD(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Ht(e,{...e._zod.def,shape:o,checks:[]})}function Oo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Vi(t){return typeof t=="string"?t:t?.message}function gr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Vi(t.inst?._zod.def?.error?.(t))??Vi(e?.error?.(t))??Vi(r.customError?.(t))??Vi(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function mS(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Xi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function gm(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function gD(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Yc,pm,cD,mm,dS,hm,pS,cm,Lr=S(()=>{Yc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};pm=Ki(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});cD=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},mm=new Set(["string","number","symbol"]),dS=new Set(["string","number","bigint","boolean","symbol","undefined"]);hm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},pS={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};cm=class{constructor(...e){}}});function ym(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function _m(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var fS,eu,Yi,bm=S(()=>{Os();Lr();fS=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,um,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},eu=T("$ZodError",fS),Yi=T("$ZodError",fS,{Parent:Error})});var xm,vm,Sm,km,wm,Io,Em,Ao,$m=S(()=>{Os();bm();Lr();xm=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new on;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gr(c,s,Ft())));throw Yc(a,o?.callee),a}return i.value},vm=xm(Yi),Sm=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gr(c,s,Ft())));throw Yc(a,o?.callee),a}return i.value},km=Sm(Yi),wm=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new on;return s.issues.length?{success:!1,error:new(t??eu)(s.issues.map(i=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Io=wm(Yi),Em=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Ao=Em(Yi)});function wS(){return new RegExp(_D,"u")}function NS(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function DS(t){return new RegExp(`^${NS(t)}$`)}function MS(t){let e=NS({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${IS}T(?:${n})$`)}var hS,gS,yS,_S,bS,xS,vS,SS,Tm,kS,_D,ES,$S,TS,PS,RS,Pm,CS,OS,IS,AS,jS,LS,zS,FS,HS,US,BS,ru=S(()=>{hS=/^[cC][^\s-]{8,}$/,gS=/^[0-9a-z]+$/,yS=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_S=/^[0-9a-vA-V]{20}$/,bS=/^[A-Za-z0-9]{27}$/,xS=/^[a-zA-Z0-9_-]{21}$/,vS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,SS=/^([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})$/,Tm=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,kS=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_D="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ES=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$S=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,TS=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,PS=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,RS=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pm=/^[A-Za-z0-9_-]*$/,CS=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,OS=/^\+(?:[0-9]){6,14}[0-9]$/,IS="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",AS=new RegExp(`^${IS}$`);jS=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},LS=/^\d+$/,zS=/^-?\d+(?:\.\d+)?/i,FS=/true|false/i,HS=/null/i,US=/^[^A-Z]*$/,BS=/^[^a-z]*$/});var it,ZS,Rm,Cm,qS,VS,WS,KS,GS,Qi,JS,XS,YS,QS,ek,tk,rk,nu=S(()=>{Os();ru();Lr();it=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ZS={number:"number",bigint:"bigint",object:"date"},Rm=T("$ZodCheckLessThan",(t,e)=>{it.init(t,e);let r=ZS[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Cm=T("$ZodCheckGreaterThan",(t,e)=>{it.init(t,e);let r=ZS[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),qS=T("$ZodCheckMultipleOf",(t,e)=>{it.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):lm(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),VS=T("$ZodCheckNumberFormat",(t,e)=>{it.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=hm[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=LS)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),WS=T("$ZodCheckMaxLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Xi(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),KS=T("$ZodCheckMinLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Xi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),GS=T("$ZodCheckLengthEquals",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Xi(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Qi=T("$ZodCheckStringFormat",(t,e)=>{var r,n;it.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),JS=T("$ZodCheckRegex",(t,e)=>{Qi.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),XS=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=US),Qi.init(t,e)}),YS=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=BS),Qi.init(t,e)}),QS=T("$ZodCheckIncludes",(t,e)=>{it.init(t,e);let r=On(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),ek=T("$ZodCheckStartsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`^${On(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),tk=T("$ZodCheckEndsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`.*${On(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),rk=T("$ZodCheckOverwrite",(t,e)=>{it.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ou,Om=S(()=>{ou=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
425
+ `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
426
+ `))}}});var ok,Im=S(()=>{ok={major:4,minor:0,patch:0}});function _k(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function bD(t){if(!Pm.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return _k(r)}function xD(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function sk(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function su(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function ik(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...jr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function ak(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>gr(s,n,Ft())))}),e}function Am(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(As(t)&&As(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Am(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Am(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function ck(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Oo(t))return t;let n=Am(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function uk(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function lk(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function dk(t,e,r){return Oo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function pk(t){return t.value=Object.freeze(t.value),t}function mk(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(gm(o))}}var ve,ea,Pe,Nm,Dm,Mm,jm,Lm,zm,Fm,Hm,Um,Bm,Zm,fk,hk,gk,yk,qm,Vm,Wm,Km,Gm,Jm,Xm,Ym,iu,Qm,ef,tf,rf,nf,of,au,cu,sf,af,cf,uf,lf,df,pf,mf,ff,hf,gf,yf,_f,bf,xf,bk=S(()=>{nu();Os();Om();$m();ru();Lr();Im();Lr();ve=T("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ok;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Oo(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,m=l._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new on;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==d&&(c||(c=Oo(s,d)))});else{if(s.issues.length===d)continue;c||(c=Oo(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new on;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Io(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ao(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ea=T("$ZodString",(t,e)=>{ve.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??jS(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Pe=T("$ZodStringFormat",(t,e)=>{Qi.init(t,e),ea.init(t,e)}),Nm=T("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=SS),Pe.init(t,e)}),Dm=T("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Tm(n))}else e.pattern??(e.pattern=Tm());Pe.init(t,e)}),Mm=T("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=kS),Pe.init(t,e)}),jm=T("$ZodURL",(t,e)=>{Pe.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:CS.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Lm=T("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=wS()),Pe.init(t,e)}),zm=T("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=xS),Pe.init(t,e)}),Fm=T("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=hS),Pe.init(t,e)}),Hm=T("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=gS),Pe.init(t,e)}),Um=T("$ZodULID",(t,e)=>{e.pattern??(e.pattern=yS),Pe.init(t,e)}),Bm=T("$ZodXID",(t,e)=>{e.pattern??(e.pattern=_S),Pe.init(t,e)}),Zm=T("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=bS),Pe.init(t,e)}),fk=T("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=MS(e)),Pe.init(t,e)}),hk=T("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=AS),Pe.init(t,e)}),gk=T("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=DS(e)),Pe.init(t,e)}),yk=T("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=vS),Pe.init(t,e)}),qm=T("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ES),Pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Vm=T("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=$S),Pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Wm=T("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=TS),Pe.init(t,e)}),Km=T("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=PS),Pe.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Gm=T("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=RS),Pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{_k(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Jm=T("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Pm),Pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{bD(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Xm=T("$ZodE164",(t,e)=>{e.pattern??(e.pattern=OS),Pe.init(t,e)});Ym=T("$ZodJWT",(t,e)=>{Pe.init(t,e),t._zod.check=r=>{xD(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),iu=T("$ZodNumber",(t,e)=>{ve.init(t,e),t._zod.pattern=t._zod.bag.pattern??zS,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Qm=T("$ZodNumber",(t,e)=>{VS.init(t,e),iu.init(t,e)}),ef=T("$ZodBoolean",(t,e)=>{ve.init(t,e),t._zod.pattern=FS,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),tf=T("$ZodNull",(t,e)=>{ve.init(t,e),t._zod.pattern=HS,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),rf=T("$ZodUnknown",(t,e)=>{ve.init(t,e),t._zod.parse=r=>r}),nf=T("$ZodNever",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});of=T("$ZodArray",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>sk(u,r,i))):sk(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});au=T("$ZodObject",(t,e)=>{ve.init(t,e);let r=Ki(()=>{let d=Object.keys(e.shape);for(let h of d)if(!(e.shape[h]instanceof ve))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let m=fm(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(m)}});Te(t._zod,"propValues",()=>{let d=e.shape,m={};for(let h in d){let p=d[h]._zod;if(p.values){m[h]??(m[h]=new Set);for(let f of p.values)m[h].add(f)}}return m});let n=d=>{let m=new ou(["shape","payload","ctx"]),h=r.value,p=_=>{let b=Co(_);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};m.write("const input = payload.value;");let f=Object.create(null),g=0;for(let _ of h.keys)f[_]=`key_${g++}`;m.write("const newResult = {}");for(let _ of h.keys)if(h.optionalKeys.has(_)){let b=f[_];m.write(`const ${b} = ${p(_)};`);let v=Co(_);m.write(`
427
+ if (${b}.issues.length) {
428
+ if (input[${v}] === undefined) {
429
+ if (${v} in input) {
430
+ newResult[${v}] = undefined;
431
+ }
432
+ } else {
433
+ payload.issues = payload.issues.concat(
434
+ ${b}.issues.map((iss) => ({
435
+ ...iss,
436
+ path: iss.path ? [${v}, ...iss.path] : [${v}],
437
+ }))
438
+ );
439
+ }
440
+ } else if (${b}.value === undefined) {
441
+ if (${v} in input) newResult[${v}] = undefined;
442
+ } else {
443
+ newResult[${v}] = ${b}.value;
444
+ }
445
+ `)}else{let b=f[_];m.write(`const ${b} = ${p(_)};`),m.write(`
446
+ if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
447
+ ...iss,
448
+ path: iss.path ? [${Co(_)}, ...iss.path] : [${Co(_)}]
449
+ })));`),m.write(`newResult[${Co(_)}] = ${b}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(_,b)=>y(d,_,b)},o,s=Is,i=!Jc.jitless,c=i&&pm.value,u=e.catchall,l;t._zod.parse=(d,m)=>{l??(l=r.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),d=o(d,m);else{d.value={};let b=l.shape;for(let v of l.keys){let E=b[v],C=E._zod.run({value:h[v],issues:[]},m),x=E._zod.optin==="optional"&&E._zod.optout==="optional";C instanceof Promise?p.push(C.then(k=>x?ik(k,d,v,h):su(k,d,v))):x?ik(C,d,v,h):su(C,d,v)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let f=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(h)){if(g.has(b))continue;if(_==="never"){f.push(b);continue}let v=y.run({value:h[b],issues:[]},m);v instanceof Promise?p.push(v.then(E=>su(E,d,b))):su(v,d,b)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),p.length?Promise.all(p).then(()=>d):d}});cu=T("$ZodUnion",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Te(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ji(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>ak(i,r,t,n)):ak(s,r,t,n)}}),sf=T("$ZodDiscriminatedUnion",(t,e)=>{cu.init(t,e);let r=t._zod.parse;Te(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Ki(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Is(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),af=T("$ZodIntersection",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ck(r,c,u)):ck(r,s,i)}});cf=T("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!As(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...jr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...jr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>gr(u,n,Ft())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...jr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...jr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),uf=T("$ZodEnum",(t,e)=>{ve.init(t,e);let r=Wi(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>mm.has(typeof n)).map(n=>typeof n=="string"?On(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),lf=T("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?On(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),df=T("$ZodTransform",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new on;return r.value=o,r}}),pf=T("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),mf=T("$ZodNullable",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(r.source)}|null)$`):void 0}),Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),ff=T("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>uk(s,e)):uk(o,e)}});hf=T("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),gf=T("$ZodNonOptional",(t,e)=>{ve.init(t,e),Te(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>lk(s,t)):lk(o,t)}});yf=T("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>gr(i,n,Ft()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gr(s,n,Ft()))},input:r.value}),r.issues=[]),r)}}),_f=T("$ZodPipe",(t,e)=>{ve.init(t,e),Te(t._zod,"values",()=>e.in._zod.values),Te(t._zod,"optin",()=>e.in._zod.optin),Te(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>dk(s,e,n)):dk(o,e,n)}});bf=T("$ZodReadonly",(t,e)=>{ve.init(t,e),Te(t._zod,"propValues",()=>e.innerType._zod.propValues),Te(t._zod,"values",()=>e.innerType._zod.values),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(pk):pk(o)}});xf=T("$ZodCustom",(t,e)=>{it.init(t,e),ve.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>mk(s,r,n,t));mk(o,r,n,t)}})});function xk(){return{localeError:SD()}}var vD,SD,vk=S(()=>{Lr();vD=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},SD=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${vD(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Qc(n.values[0])}`:`Invalid option: expected one of ${Xc(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Xc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var uu=S(()=>{});function Sk(){return new ta}var ta,In,Sf=S(()=>{ta=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};In=Sk()});function kf(t,e){return new t({type:"string",...X(e)})}function wf(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function lu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function Ef(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function $f(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function Tf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function Pf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function Rf(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function Cf(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function Of(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function If(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function Af(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function Nf(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function Df(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function Mf(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function jf(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function Lf(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function zf(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function Ff(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function Hf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function Uf(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function Bf(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function Zf(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function kk(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function wk(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function Ek(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function $k(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function qf(t,e){return new t({type:"number",checks:[],...X(e)})}function Vf(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function Wf(t,e){return new t({type:"boolean",...X(e)})}function Kf(t,e){return new t({type:"null",...X(e)})}function Gf(t){return new t({type:"unknown"})}function Jf(t,e){return new t({type:"never",...X(e)})}function du(t,e){return new Rm({check:"less_than",...X(e),value:t,inclusive:!1})}function ra(t,e){return new Rm({check:"less_than",...X(e),value:t,inclusive:!0})}function pu(t,e){return new Cm({check:"greater_than",...X(e),value:t,inclusive:!1})}function na(t,e){return new Cm({check:"greater_than",...X(e),value:t,inclusive:!0})}function mu(t,e){return new qS({check:"multiple_of",...X(e),value:t})}function fu(t,e){return new WS({check:"max_length",...X(e),maximum:t})}function Ns(t,e){return new KS({check:"min_length",...X(e),minimum:t})}function hu(t,e){return new GS({check:"length_equals",...X(e),length:t})}function Xf(t,e){return new JS({check:"string_format",format:"regex",...X(e),pattern:t})}function Yf(t){return new XS({check:"string_format",format:"lowercase",...X(t)})}function Qf(t){return new YS({check:"string_format",format:"uppercase",...X(t)})}function eh(t,e){return new QS({check:"string_format",format:"includes",...X(e),includes:t})}function th(t,e){return new ek({check:"string_format",format:"starts_with",...X(e),prefix:t})}function rh(t,e){return new tk({check:"string_format",format:"ends_with",...X(e),suffix:t})}function No(t){return new rk({check:"overwrite",tx:t})}function nh(t){return No(e=>e.normalize(t))}function oh(){return No(t=>t.trim())}function sh(){return No(t=>t.toLowerCase())}function ih(){return No(t=>t.toUpperCase())}function Tk(t,e,r){return new t({type:"array",element:e,...X(r)})}function ah(t,e,r){let n=X(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function ch(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}var Pk=S(()=>{nu();Lr()});var Rk=S(()=>{});function uh(t,e){if(t instanceof ta){let n=new gu(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new gu(e);return r.process(t),r.emit(t,e)}function Ye(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ye(o.element,r);case"object":{for(let s in o.shape)if(Ye(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ye(s,r))return!0;return!1}case"intersection":return Ye(o.left,r)||Ye(o.right,r);case"tuple":{for(let s of o.items)if(Ye(s,r))return!0;return!!(o.rest&&Ye(o.rest,r))}case"record":return Ye(o.keyType,r)||Ye(o.valueType,r);case"map":return Ye(o.keyType,r)||Ye(o.valueType,r);case"set":return Ye(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ye(o.innerType,r);case"lazy":return Ye(o.getter(),r);case"default":return Ye(o.innerType,r);case"prefault":return Ye(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ye(o.in,r)||Ye(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var gu,Ck=S(()=>{Sf();Lr();gu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??In,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,d),this.seen.get(m).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let p=h;p.type="string";let{minimum:f,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof f=="number"&&(p.minLength=f),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),b&&(p.contentEncoding=b),_&&_.size>0){let v=[..._];v.length===1?p.pattern=v[0].source:v.length>1&&(a.schema.allOf=[...v.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let p=h,{minimum:f,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:v}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof v=="number"&&(p.exclusiveMinimum=v),typeof f=="number"&&(p.minimum=f,typeof v=="number"&&(v>=f?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{let p=h;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(p.minItems=f),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=h;p.type="object",p.properties={};let f=o.shape;for(let _ in f)p.properties[_]=this.process(f[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(_=>{let b=o.shape[_]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=h;p.anyOf=o.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=h,f=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,_=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=h;p.type="array";let f=o.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?p.prefixItems=f:p.items=f,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=h;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=h,f=Wi(o.entries);f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),p.enum=f;break}case"literal":{let p=h,f=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];p.type=g===null?"null":typeof g,p.const=g}else f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),f.every(g=>typeof g=="boolean")&&(p.type="string"),f.every(g=>g===null)&&(p.type="null"),p.enum=f;break}case"file":{let p=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),_?_.length===1?(f.contentMediaType=_[0],Object.assign(p,f)):p.anyOf=_.map(b=>({...f,contentMediaType:b})):Object.assign(p,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,d);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=h;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=f.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,d),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Ye(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let f=n.external.registry.get(l[0])?.id,g=n.external.uri??(_=>_);if(f)return{ref:g(f)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let h=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:m,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);let p=d.schema;for(let f in p)delete p[f];p.$ref=m};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
450
+
451
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let h=n.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let m=this.seen.get(l),h=m.def??m.schema,p={...h};if(m.ref===null)return;let f=m.ref;if(m.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,p))}m.isParent||this.override({zodSchema:l,jsonSchema:h,path:m.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Ok=S(()=>{});var kt=S(()=>{Os();$m();bm();bk();nu();Im();Lr();ru();uu();Sf();Om();Rk();Pk();Ck();Ok()});var lh=S(()=>{kt()});function dh(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new o1(r)}var n1,o1,Ik=S(()=>{kt();kt();lh();n1=T("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>vm(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Io(t,r,n),t.parseAsync=async(r,n)=>km(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ao(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),o1=T("ZodMiniObject",(t,e)=>{au.init(t,e),n1.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var Ak=S(()=>{});var Nk=S(()=>{});var Dk=S(()=>{});var Mk=S(()=>{kt();lh();Ik();Ak();kt();uu();Nk();Dk()});var jk=S(()=>{Mk()});var ph=S(()=>{jk()});function nr(t){return!!t._zod}function Mo(t){let e=Object.values(t);if(e.length===0)return dh({});let r=e.every(nr),n=e.every(o=>!nr(o));if(r)return dh(t);if(n)return im(t);throw new Error("Mixed Zod versions detected in object shape.")}function An(t,e){return nr(t)?Io(t,e):t.safeParse(e)}async function yu(t,e){return nr(t)?await Ao(t,e):await t.safeParseAsync(e)}function Nn(t){if(!t)return;let e;if(nr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ds(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Mo(t)}}if(nr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function _u(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function zk(t){return t.description}function Fk(t){if(nr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function bu(t){if(nr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var oa=S(()=>{qi();ph()});var mh=S(()=>{kt()});var sa={};we(sa,{ZodISODate:()=>Uk,ZodISODateTime:()=>Hk,ZodISODuration:()=>Zk,ZodISOTime:()=>Bk,date:()=>hh,datetime:()=>fh,duration:()=>yh,time:()=>gh});function fh(t){return kk(Hk,t)}function hh(t){return wk(Uk,t)}function gh(t){return Ek(Bk,t)}function yh(t){return $k(Zk,t)}var Hk,Uk,Bk,Zk,_h=S(()=>{kt();bh();Hk=T("ZodISODateTime",(t,e)=>{fk.init(t,e),Me.init(t,e)});Uk=T("ZodISODate",(t,e)=>{hk.init(t,e),Me.init(t,e)});Bk=T("ZodISOTime",(t,e)=>{gk.init(t,e),Me.init(t,e)});Zk=T("ZodISODuration",(t,e)=>{yk.init(t,e),Me.init(t,e)})});var qk,t6,ia,xh=S(()=>{kt();kt();qk=(t,e)=>{eu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>_m(t,r)},flatten:{value:r=>ym(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},t6=T("ZodError",qk),ia=T("ZodError",qk,{Parent:Error})});var Vk,Wk,Kk,Gk,vh=S(()=>{kt();xh();Vk=xm(ia),Wk=Sm(ia),Kk=wm(ia),Gk=Em(ia)});function $(t){return kf(f1,t)}function ye(t){return qf(e0,t)}function Xk(t){return Vf(I1,t)}function ot(t){return Wf(A1,t)}function t0(t){return Kf(N1,t)}function je(){return Gf(D1)}function j1(t){return Jf(M1,t)}function le(t,e){return Tk(L1,t,e)}function H(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new r0(r)}function wt(t,e){return new r0({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:je(),...ue.normalizeParams(e)})}function Ie(t,e){return new n0({type:"union",options:t,...ue.normalizeParams(e)})}function wh(t,e,r){return new z1({type:"union",options:e,discriminator:t,...ue.normalizeParams(r)})}function vu(t,e){return new F1({type:"intersection",left:t,right:e})}function Re(t,e,r){return new H1({type:"record",keyType:t,valueType:e,...ue.normalizeParams(r)})}function At(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Sh({type:"enum",entries:r,...ue.normalizeParams(e)})}function q(t,e){return new U1({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function o0(t){return new B1({type:"transform",transform:t})}function Le(t){return new s0({type:"optional",innerType:t})}function Yk(t){return new Z1({type:"nullable",innerType:t})}function V1(t,e){return new q1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function K1(t,e){return new W1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function G1(t,e){return new i0({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function X1(t,e){return new J1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function kh(t,e){return new Y1({type:"pipe",in:t,out:e})}function eM(t){return new Q1({type:"readonly",innerType:t})}function tM(t){let e=new it({check:"custom"});return e._zod.check=t,e}function c0(t,e){return ah(a0,t??(()=>!0),e)}function rM(t,e={}){return ch(a0,t,e)}function nM(t){let e=tM(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ue.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ue.issue(o))}},t(r.value,r)));return e}function Eh(t,e){return kh(o0(t),e)}var Ue,Qk,f1,Me,h1,Jk,xu,g1,y1,_1,b1,x1,v1,S1,k1,w1,E1,$1,T1,P1,R1,C1,O1,e0,I1,A1,N1,D1,M1,L1,r0,n0,z1,F1,H1,Sh,U1,B1,s0,Z1,q1,W1,i0,J1,Y1,Q1,a0,bh=S(()=>{kt();kt();mh();_h();vh();Ue=T("ZodType",(t,e)=>(ve.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Vk(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Kk(t,r,n),t.parseAsync=async(r,n)=>Wk(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Gk(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(rM(r,n)),t.superRefine=r=>t.check(nM(r)),t.overwrite=r=>t.check(No(r)),t.optional=()=>Le(t),t.nullable=()=>Yk(t),t.nullish=()=>Le(Yk(t)),t.nonoptional=r=>G1(t,r),t.array=()=>le(t),t.or=r=>Ie([t,r]),t.and=r=>vu(t,r),t.transform=r=>kh(t,o0(r)),t.default=r=>V1(t,r),t.prefault=r=>K1(t,r),t.catch=r=>X1(t,r),t.pipe=r=>kh(t,r),t.readonly=()=>eM(t),t.describe=r=>{let n=t.clone();return In.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return In.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return In.get(t);let n=t.clone();return In.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Qk=T("_ZodString",(t,e)=>{ea.init(t,e),Ue.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Xf(...n)),t.includes=(...n)=>t.check(eh(...n)),t.startsWith=(...n)=>t.check(th(...n)),t.endsWith=(...n)=>t.check(rh(...n)),t.min=(...n)=>t.check(Ns(...n)),t.max=(...n)=>t.check(fu(...n)),t.length=(...n)=>t.check(hu(...n)),t.nonempty=(...n)=>t.check(Ns(1,...n)),t.lowercase=n=>t.check(Yf(n)),t.uppercase=n=>t.check(Qf(n)),t.trim=()=>t.check(oh()),t.normalize=(...n)=>t.check(nh(...n)),t.toLowerCase=()=>t.check(sh()),t.toUpperCase=()=>t.check(ih())}),f1=T("ZodString",(t,e)=>{ea.init(t,e),Qk.init(t,e),t.email=r=>t.check(wf(h1,r)),t.url=r=>t.check(Rf(g1,r)),t.jwt=r=>t.check(Zf(O1,r)),t.emoji=r=>t.check(Cf(y1,r)),t.guid=r=>t.check(lu(Jk,r)),t.uuid=r=>t.check(Ef(xu,r)),t.uuidv4=r=>t.check($f(xu,r)),t.uuidv6=r=>t.check(Tf(xu,r)),t.uuidv7=r=>t.check(Pf(xu,r)),t.nanoid=r=>t.check(Of(_1,r)),t.guid=r=>t.check(lu(Jk,r)),t.cuid=r=>t.check(If(b1,r)),t.cuid2=r=>t.check(Af(x1,r)),t.ulid=r=>t.check(Nf(v1,r)),t.base64=r=>t.check(Hf(P1,r)),t.base64url=r=>t.check(Uf(R1,r)),t.xid=r=>t.check(Df(S1,r)),t.ksuid=r=>t.check(Mf(k1,r)),t.ipv4=r=>t.check(jf(w1,r)),t.ipv6=r=>t.check(Lf(E1,r)),t.cidrv4=r=>t.check(zf($1,r)),t.cidrv6=r=>t.check(Ff(T1,r)),t.e164=r=>t.check(Bf(C1,r)),t.datetime=r=>t.check(fh(r)),t.date=r=>t.check(hh(r)),t.time=r=>t.check(gh(r)),t.duration=r=>t.check(yh(r))});Me=T("ZodStringFormat",(t,e)=>{Pe.init(t,e),Qk.init(t,e)}),h1=T("ZodEmail",(t,e)=>{Mm.init(t,e),Me.init(t,e)}),Jk=T("ZodGUID",(t,e)=>{Nm.init(t,e),Me.init(t,e)}),xu=T("ZodUUID",(t,e)=>{Dm.init(t,e),Me.init(t,e)}),g1=T("ZodURL",(t,e)=>{jm.init(t,e),Me.init(t,e)}),y1=T("ZodEmoji",(t,e)=>{Lm.init(t,e),Me.init(t,e)}),_1=T("ZodNanoID",(t,e)=>{zm.init(t,e),Me.init(t,e)}),b1=T("ZodCUID",(t,e)=>{Fm.init(t,e),Me.init(t,e)}),x1=T("ZodCUID2",(t,e)=>{Hm.init(t,e),Me.init(t,e)}),v1=T("ZodULID",(t,e)=>{Um.init(t,e),Me.init(t,e)}),S1=T("ZodXID",(t,e)=>{Bm.init(t,e),Me.init(t,e)}),k1=T("ZodKSUID",(t,e)=>{Zm.init(t,e),Me.init(t,e)}),w1=T("ZodIPv4",(t,e)=>{qm.init(t,e),Me.init(t,e)}),E1=T("ZodIPv6",(t,e)=>{Vm.init(t,e),Me.init(t,e)}),$1=T("ZodCIDRv4",(t,e)=>{Wm.init(t,e),Me.init(t,e)}),T1=T("ZodCIDRv6",(t,e)=>{Km.init(t,e),Me.init(t,e)}),P1=T("ZodBase64",(t,e)=>{Gm.init(t,e),Me.init(t,e)}),R1=T("ZodBase64URL",(t,e)=>{Jm.init(t,e),Me.init(t,e)}),C1=T("ZodE164",(t,e)=>{Xm.init(t,e),Me.init(t,e)}),O1=T("ZodJWT",(t,e)=>{Ym.init(t,e),Me.init(t,e)}),e0=T("ZodNumber",(t,e)=>{iu.init(t,e),Ue.init(t,e),t.gt=(n,o)=>t.check(pu(n,o)),t.gte=(n,o)=>t.check(na(n,o)),t.min=(n,o)=>t.check(na(n,o)),t.lt=(n,o)=>t.check(du(n,o)),t.lte=(n,o)=>t.check(ra(n,o)),t.max=(n,o)=>t.check(ra(n,o)),t.int=n=>t.check(Xk(n)),t.safe=n=>t.check(Xk(n)),t.positive=n=>t.check(pu(0,n)),t.nonnegative=n=>t.check(na(0,n)),t.negative=n=>t.check(du(0,n)),t.nonpositive=n=>t.check(ra(0,n)),t.multipleOf=(n,o)=>t.check(mu(n,o)),t.step=(n,o)=>t.check(mu(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});I1=T("ZodNumberFormat",(t,e)=>{Qm.init(t,e),e0.init(t,e)});A1=T("ZodBoolean",(t,e)=>{ef.init(t,e),Ue.init(t,e)});N1=T("ZodNull",(t,e)=>{tf.init(t,e),Ue.init(t,e)});D1=T("ZodUnknown",(t,e)=>{rf.init(t,e),Ue.init(t,e)});M1=T("ZodNever",(t,e)=>{nf.init(t,e),Ue.init(t,e)});L1=T("ZodArray",(t,e)=>{of.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Ns(r,n)),t.nonempty=r=>t.check(Ns(1,r)),t.max=(r,n)=>t.check(fu(r,n)),t.length=(r,n)=>t.check(hu(r,n)),t.unwrap=()=>t.element});r0=T("ZodObject",(t,e)=>{au.init(t,e),Ue.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:je()}),t.loose=()=>t.clone({...t._zod.def,catchall:je()}),t.strict=()=>t.clone({...t._zod.def,catchall:j1()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ue.extend(t,r),t.merge=r=>ue.merge(t,r),t.pick=r=>ue.pick(t,r),t.omit=r=>ue.omit(t,r),t.partial=(...r)=>ue.partial(s0,t,r[0]),t.required=(...r)=>ue.required(i0,t,r[0])});n0=T("ZodUnion",(t,e)=>{cu.init(t,e),Ue.init(t,e),t.options=e.options});z1=T("ZodDiscriminatedUnion",(t,e)=>{n0.init(t,e),sf.init(t,e)});F1=T("ZodIntersection",(t,e)=>{af.init(t,e),Ue.init(t,e)});H1=T("ZodRecord",(t,e)=>{cf.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Sh=T("ZodEnum",(t,e)=>{uf.init(t,e),Ue.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Sh({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Sh({...e,checks:[],...ue.normalizeParams(o),entries:s})}});U1=T("ZodLiteral",(t,e)=>{lf.init(t,e),Ue.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});B1=T("ZodTransform",(t,e)=>{df.init(t,e),Ue.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ue.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ue.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});s0=T("ZodOptional",(t,e)=>{pf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});Z1=T("ZodNullable",(t,e)=>{mf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});q1=T("ZodDefault",(t,e)=>{ff.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});W1=T("ZodPrefault",(t,e)=>{hf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});i0=T("ZodNonOptional",(t,e)=>{gf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});J1=T("ZodCatch",(t,e)=>{yf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Y1=T("ZodPipe",(t,e)=>{_f.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});Q1=T("ZodReadonly",(t,e)=>{bf.init(t,e),Ue.init(t,e)});a0=T("ZodCustom",(t,e)=>{xf.init(t,e),Ue.init(t,e)})});var u0=S(()=>{});var l0=S(()=>{});var d0=S(()=>{kt();bh();mh();xh();vh();u0();kt();vk();uu();_h();l0();Ft(xk())});var p0=S(()=>{d0()});var m0=S(()=>{p0()});function C0(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function O0(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Th,f0,Dn,ku,Qe,h0,g0,y6,iM,aM,Ph,Ut,aa,y0,at,or,sr,ct,wu,_0,Rh,b0,x0,Ch,ca,G,Oh,v0,S0,_6,Eu,cM,$u,uM,ua,Ms,k0,lM,dM,pM,mM,fM,hM,Ih,gM,yM,Ah,Tu,_M,bM,Pu,xM,la,da,vM,pa,js,SM,ma,Ru,Cu,Ou,b6,Iu,Au,Nu,w0,E0,$0,Nh,T0,fa,Ls,P0,kM,zs,wM,Fs,EM,Dh,$M,Du,TM,PM,RM,CM,OM,IM,AM,NM,DM,MM,Hs,jM,LM,Mu,Mh,jh,Lh,zM,FM,HM,zh,UM,BM,ZM,qM,VM,R0,Us,WM,ju,x6,KM,Bs,GM,v6,ha,JM,Fh,XM,YM,QM,ej,tj,rj,nj,Su,oj,sj,ij,ga,Hh,aj,cj,uj,lj,dj,pj,mj,fj,hj,gj,yj,_j,bj,xj,vj,Sj,kj,wj,Zs,Ej,$j,Tj,Lu,Pj,Rj,Cj,Uh,Oj,S6,k6,w6,E6,$6,T6,B,$h,jo=S(()=>{m0();Th="2025-11-25",f0=[Th,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Dn="io.modelcontextprotocol/related-task",ku="2.0",Qe=c0(t=>t!==null&&(typeof t=="object"||typeof t=="function")),h0=Ie([$(),ye().int()]),g0=$(),y6=wt({ttl:ye().optional(),pollInterval:ye().optional()}),iM=H({ttl:ye().optional()}),aM=H({taskId:$()}),Ph=wt({progressToken:h0.optional(),[Dn]:aM.optional()}),Ut=H({_meta:Ph.optional()}),aa=Ut.extend({task:iM.optional()}),y0=t=>aa.safeParse(t).success,at=H({method:$(),params:Ut.loose().optional()}),or=H({_meta:Ph.optional()}),sr=H({method:$(),params:or.loose().optional()}),ct=wt({_meta:Ph.optional()}),wu=Ie([$(),ye().int()]),_0=H({jsonrpc:q(ku),id:wu,...at.shape}).strict(),Rh=t=>_0.safeParse(t).success,b0=H({jsonrpc:q(ku),...sr.shape}).strict(),x0=t=>b0.safeParse(t).success,Ch=H({jsonrpc:q(ku),id:wu,result:ct}).strict(),ca=t=>Ch.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(G||(G={}));Oh=H({jsonrpc:q(ku),id:wu.optional(),error:H({code:ye().int(),message:$(),data:je().optional()})}).strict(),v0=t=>Oh.safeParse(t).success,S0=Ie([_0,b0,Ch,Oh]),_6=Ie([Ch,Oh]),Eu=ct.strict(),cM=or.extend({requestId:wu.optional(),reason:$().optional()}),$u=sr.extend({method:q("notifications/cancelled"),params:cM}),uM=H({src:$(),mimeType:$().optional(),sizes:le($()).optional(),theme:At(["light","dark"]).optional()}),ua=H({icons:le(uM).optional()}),Ms=H({name:$(),title:$().optional()}),k0=Ms.extend({...Ms.shape,...ua.shape,version:$(),websiteUrl:$().optional(),description:$().optional()}),lM=vu(H({applyDefaults:ot().optional()}),Re($(),je())),dM=Eh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,vu(H({form:lM.optional(),url:Qe.optional()}),Re($(),je()).optional())),pM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({sampling:wt({createMessage:Qe.optional()}).optional(),elicitation:wt({create:Qe.optional()}).optional()}).optional()}),mM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({tools:wt({call:Qe.optional()}).optional()}).optional()}),fM=H({experimental:Re($(),Qe).optional(),sampling:H({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:dM.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:pM.optional(),extensions:Re($(),Qe).optional()}),hM=Ut.extend({protocolVersion:$(),capabilities:fM,clientInfo:k0}),Ih=at.extend({method:q("initialize"),params:hM}),gM=H({experimental:Re($(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:mM.optional(),extensions:Re($(),Qe).optional()}),yM=ct.extend({protocolVersion:$(),capabilities:gM,serverInfo:k0,instructions:$().optional()}),Ah=sr.extend({method:q("notifications/initialized"),params:or.optional()}),Tu=at.extend({method:q("ping"),params:Ut.optional()}),_M=H({progress:ye(),total:Le(ye()),message:Le($())}),bM=H({...or.shape,..._M.shape,progressToken:h0}),Pu=sr.extend({method:q("notifications/progress"),params:bM}),xM=Ut.extend({cursor:g0.optional()}),la=at.extend({params:xM.optional()}),da=ct.extend({nextCursor:g0.optional()}),vM=At(["working","input_required","completed","failed","cancelled"]),pa=H({taskId:$(),status:vM,ttl:Ie([ye(),t0()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:Le(ye()),statusMessage:Le($())}),js=ct.extend({task:pa}),SM=or.merge(pa),ma=sr.extend({method:q("notifications/tasks/status"),params:SM}),Ru=at.extend({method:q("tasks/get"),params:Ut.extend({taskId:$()})}),Cu=ct.merge(pa),Ou=at.extend({method:q("tasks/result"),params:Ut.extend({taskId:$()})}),b6=ct.loose(),Iu=la.extend({method:q("tasks/list")}),Au=da.extend({tasks:le(pa)}),Nu=at.extend({method:q("tasks/cancel"),params:Ut.extend({taskId:$()})}),w0=ct.merge(pa),E0=H({uri:$(),mimeType:Le($()),_meta:Re($(),je()).optional()}),$0=E0.extend({text:$()}),Nh=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),T0=E0.extend({blob:Nh}),fa=At(["user","assistant"]),Ls=H({audience:le(fa).optional(),priority:ye().min(0).max(1).optional(),lastModified:sa.datetime({offset:!0}).optional()}),P0=H({...Ms.shape,...ua.shape,uri:$(),description:Le($()),mimeType:Le($()),size:Le(ye()),annotations:Ls.optional(),_meta:Le(wt({}))}),kM=H({...Ms.shape,...ua.shape,uriTemplate:$(),description:Le($()),mimeType:Le($()),annotations:Ls.optional(),_meta:Le(wt({}))}),zs=la.extend({method:q("resources/list")}),wM=da.extend({resources:le(P0)}),Fs=la.extend({method:q("resources/templates/list")}),EM=da.extend({resourceTemplates:le(kM)}),Dh=Ut.extend({uri:$()}),$M=Dh,Du=at.extend({method:q("resources/read"),params:$M}),TM=ct.extend({contents:le(Ie([$0,T0]))}),PM=sr.extend({method:q("notifications/resources/list_changed"),params:or.optional()}),RM=Dh,CM=at.extend({method:q("resources/subscribe"),params:RM}),OM=Dh,IM=at.extend({method:q("resources/unsubscribe"),params:OM}),AM=or.extend({uri:$()}),NM=sr.extend({method:q("notifications/resources/updated"),params:AM}),DM=H({name:$(),description:Le($()),required:Le(ot())}),MM=H({...Ms.shape,...ua.shape,description:Le($()),arguments:Le(le(DM)),_meta:Le(wt({}))}),Hs=la.extend({method:q("prompts/list")}),jM=da.extend({prompts:le(MM)}),LM=Ut.extend({name:$(),arguments:Re($(),$()).optional()}),Mu=at.extend({method:q("prompts/get"),params:LM}),Mh=H({type:q("text"),text:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),jh=H({type:q("image"),data:Nh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),Lh=H({type:q("audio"),data:Nh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),zM=H({type:q("tool_use"),name:$(),id:$(),input:Re($(),je()),_meta:Re($(),je()).optional()}),FM=H({type:q("resource"),resource:Ie([$0,T0]),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),HM=P0.extend({type:q("resource_link")}),zh=Ie([Mh,jh,Lh,HM,FM]),UM=H({role:fa,content:zh}),BM=ct.extend({description:$().optional(),messages:le(UM)}),ZM=sr.extend({method:q("notifications/prompts/list_changed"),params:or.optional()}),qM=H({title:$().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),VM=H({taskSupport:At(["required","optional","forbidden"]).optional()}),R0=H({...Ms.shape,...ua.shape,description:$().optional(),inputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()),outputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()).optional(),annotations:qM.optional(),execution:VM.optional(),_meta:Re($(),je()).optional()}),Us=la.extend({method:q("tools/list")}),WM=da.extend({tools:le(R0)}),ju=ct.extend({content:le(zh).default([]),structuredContent:Re($(),je()).optional(),isError:ot().optional()}),x6=ju.or(ct.extend({toolResult:je()})),KM=aa.extend({name:$(),arguments:Re($(),je()).optional()}),Bs=at.extend({method:q("tools/call"),params:KM}),GM=sr.extend({method:q("notifications/tools/list_changed"),params:or.optional()}),v6=H({autoRefresh:ot().default(!0),debounceMs:ye().int().nonnegative().default(300)}),ha=At(["debug","info","notice","warning","error","critical","alert","emergency"]),JM=Ut.extend({level:ha}),Fh=at.extend({method:q("logging/setLevel"),params:JM}),XM=or.extend({level:ha,logger:$().optional(),data:je()}),YM=sr.extend({method:q("notifications/message"),params:XM}),QM=H({name:$().optional()}),ej=H({hints:le(QM).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),tj=H({mode:At(["auto","required","none"]).optional()}),rj=H({type:q("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:le(zh).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:Re($(),je()).optional()}),nj=wh("type",[Mh,jh,Lh]),Su=wh("type",[Mh,jh,Lh,zM,rj]),oj=H({role:fa,content:Ie([Su,le(Su)]),_meta:Re($(),je()).optional()}),sj=aa.extend({messages:le(oj),modelPreferences:ej.optional(),systemPrompt:$().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le($()).optional(),metadata:Qe.optional(),tools:le(R0).optional(),toolChoice:tj.optional()}),ij=at.extend({method:q("sampling/createMessage"),params:sj}),ga=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens"]).or($())),role:fa,content:nj}),Hh=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:fa,content:Ie([Su,le(Su)])}),aj=H({type:q("boolean"),title:$().optional(),description:$().optional(),default:ot().optional()}),cj=H({type:q("string"),title:$().optional(),description:$().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:At(["email","uri","date","date-time"]).optional(),default:$().optional()}),uj=H({type:At(["number","integer"]),title:$().optional(),description:$().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),lj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),default:$().optional()}),dj=H({type:q("string"),title:$().optional(),description:$().optional(),oneOf:le(H({const:$(),title:$()})),default:$().optional()}),pj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),enumNames:le($()).optional(),default:$().optional()}),mj=Ie([lj,dj]),fj=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({type:q("string"),enum:le($())}),default:le($()).optional()}),hj=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({anyOf:le(H({const:$(),title:$()}))}),default:le($()).optional()}),gj=Ie([fj,hj]),yj=Ie([pj,mj,gj]),_j=Ie([yj,aj,cj,uj]),bj=aa.extend({mode:q("form").optional(),message:$(),requestedSchema:H({type:q("object"),properties:Re($(),_j),required:le($()).optional()})}),xj=aa.extend({mode:q("url"),message:$(),elicitationId:$(),url:$().url()}),vj=Ie([bj,xj]),Sj=at.extend({method:q("elicitation/create"),params:vj}),kj=or.extend({elicitationId:$()}),wj=sr.extend({method:q("notifications/elicitation/complete"),params:kj}),Zs=ct.extend({action:At(["accept","decline","cancel"]),content:Eh(t=>t===null?void 0:t,Re($(),Ie([$(),ye(),ot(),le($())])).optional())}),Ej=H({type:q("ref/resource"),uri:$()}),$j=H({type:q("ref/prompt"),name:$()}),Tj=Ut.extend({ref:Ie([$j,Ej]),argument:H({name:$(),value:$()}),context:H({arguments:Re($(),$()).optional()}).optional()}),Lu=at.extend({method:q("completion/complete"),params:Tj});Pj=ct.extend({completion:wt({values:le($()).max(100),total:Le(ye().int()),hasMore:Le(ot())})}),Rj=H({uri:$().startsWith("file://"),name:$().optional(),_meta:Re($(),je()).optional()}),Cj=at.extend({method:q("roots/list"),params:Ut.optional()}),Uh=ct.extend({roots:le(Rj)}),Oj=sr.extend({method:q("notifications/roots/list_changed"),params:or.optional()}),S6=Ie([Tu,Ih,Lu,Fh,Mu,Hs,zs,Fs,Du,CM,IM,Bs,Us,Ru,Ou,Iu,Nu]),k6=Ie([$u,Pu,Ah,Oj,ma]),w6=Ie([Eu,ga,Hh,Zs,Uh,Cu,Au,js]),E6=Ie([Tu,ij,Sj,Cj,Ru,Ou,Iu,Nu]),$6=Ie([$u,Pu,YM,NM,PM,GM,ZM,ma,wj]),T6=Ie([Eu,yM,Pj,BM,jM,wM,EM,TM,ju,WM,Cu,Au,js]),B=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new $h(o.elicitations,r)}return new t(e,r,n)}},$h=class extends B{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Mn(t){return t==="completed"||t==="failed"||t==="cancelled"}var I0=S(()=>{});var N0,A0,D0,zu=S(()=>{N0=Symbol("Let zodToJsonSchema decide on which parser to use"),A0={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},D0=t=>typeof t=="string"?{...A0,name:t}:{...A0,...t}});var M0,Bh=S(()=>{zu();M0=t=>{let e=D0(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Zh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,o){t[e]=r,Zh(t,e,n,o)}var jn=S(()=>{});var Fu,Hu=S(()=>{Fu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function ze(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Fu(e,t.currentPath):e.join("/")}}var ir=S(()=>{Hu()});function j0(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var qh=S(()=>{qi();jn();Ge()});function L0(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var Vh=S(()=>{jn()});function z0(){return{type:"boolean"}}var Wh=S(()=>{});function Uu(t,e){return Y(t.type._def,e)}var Bu=S(()=>{Ge()});var F0,Kh=S(()=>{Ge();F0=(t,e)=>Y(t.innerType._def,e)});function Gh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Gh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ij(t,e)}}var Ij,Jh=S(()=>{jn();Ij=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function H0(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Xh=S(()=>{Ge()});function U0(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):ze(e)}var Yh=S(()=>{Ge();ir()});function B0(t){return{type:"string",enum:Array.from(t.values)}}var Qh=S(()=>{});function Z0(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Aj(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var Aj,eg=S(()=>{Ge();Aj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function q0(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var tg=S(()=>{});function Zu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":_r(r,"email",n.message,e);break;case"format:idn-email":_r(r,"idn-email",n.message,e);break;case"pattern:zod":Et(r,yr.email,n.message,e);break}break;case"url":_r(r,"uri",n.message,e);break;case"uuid":_r(r,"uuid",n.message,e);break;case"regex":Et(r,n.regex,n.message,e);break;case"cuid":Et(r,yr.cuid,n.message,e);break;case"cuid2":Et(r,yr.cuid2,n.message,e);break;case"startsWith":Et(r,RegExp(`^${ng(n.value,e)}`),n.message,e);break;case"endsWith":Et(r,RegExp(`${ng(n.value,e)}$`),n.message,e);break;case"datetime":_r(r,"date-time",n.message,e);break;case"date":_r(r,"date",n.message,e);break;case"time":_r(r,"time",n.message,e);break;case"duration":_r(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Et(r,RegExp(ng(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&_r(r,"ipv4",n.message,e),n.version!=="v4"&&_r(r,"ipv6",n.message,e);break}case"base64url":Et(r,yr.base64url,n.message,e);break;case"jwt":Et(r,yr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Et(r,yr.ipv4Cidr,n.message,e),n.version!=="v4"&&Et(r,yr.ipv6Cidr,n.message,e);break}case"emoji":Et(r,yr.emoji(),n.message,e);break;case"ulid":{Et(r,yr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{_r(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Et(r,yr.base64,n.message,e);break}}break}case"nanoid":Et(r,yr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ng(t,e){return e.patternStrategy==="escape"?Dj(t):t}function Dj(t){let e="";for(let r=0;r<t.length;r++)Nj.has(t[r])||(e+="\\"),e+=t[r];return e}function _r(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):de(t,"format",e,r,n)}function Et(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:V0(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",V0(e,n),r,n)}function V0(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
452
+ ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
453
+ ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
454
+ `:`[${n[c]}\r
455
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var rg,yr,Nj,qu=S(()=>{jn();yr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(rg===void 0&&(rg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rg),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};Nj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Vu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Zu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Uu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Wu=S(()=>{qi();Ge();qu();Bu();ir()});function W0(t,e){if(e.mapStrategy==="record")return Vu(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ze(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var og=S(()=>{Ge();Wu();ir()});function K0(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var sg=S(()=>{});function G0(t){return t.target==="openAi"?void 0:{not:ze({...t,currentPath:[...t.currentPath,"not"]})}}var ig=S(()=>{ir()});function J0(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ag=S(()=>{});function Y0(t,e){if(e.target==="openApi3")return X0(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ya&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ya[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return X0(t,e)}var ya,X0,Ku=S(()=>{Ge();ya={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};X0=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Q0(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ya[t.innerType._def.typeName],nullable:!0}:{type:[ya[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var cg=S(()=>{Ge();Ku()});function ew(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Zh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var ug=S(()=>{jn()});function tw(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=jj(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Y(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=Mj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Mj(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function jj(t){try{return t.isOptional()}catch{return!0}}var lg=S(()=>{Ge()});var rw,dg=S(()=>{Ge();ir();rw=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ze(e)},r]}:ze(e)}});var nw,pg=S(()=>{Ge();nw=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let r=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function ow(t,e){return Y(t.type._def,e)}var mg=S(()=>{Ge()});function sw(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var fg=S(()=>{jn();Ge()});function iw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var hg=S(()=>{Ge()});function aw(t){return{not:ze(t)}}var gg=S(()=>{ir()});function cw(t){return ze(t)}var yg=S(()=>{ir()});var uw,_g=S(()=>{Ge();uw=(t,e)=>Y(t.innerType._def,e)});var lw,bg=S(()=>{qi();ir();qh();Vh();Wh();Bu();Kh();Jh();Xh();Yh();Qh();eg();tg();og();sg();ig();ag();cg();ug();lg();dg();pg();mg();Wu();fg();qu();hg();gg();Ku();yg();_g();lw=(t,e,r)=>{switch(e){case D.ZodString:return Zu(t,r);case D.ZodNumber:return ew(t,r);case D.ZodObject:return tw(t,r);case D.ZodBigInt:return L0(t,r);case D.ZodBoolean:return z0();case D.ZodDate:return Gh(t,r);case D.ZodUndefined:return aw(r);case D.ZodNull:return J0(r);case D.ZodArray:return j0(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return Y0(t,r);case D.ZodIntersection:return Z0(t,r);case D.ZodTuple:return iw(t,r);case D.ZodRecord:return Vu(t,r);case D.ZodLiteral:return q0(t,r);case D.ZodEnum:return B0(t);case D.ZodNativeEnum:return K0(t);case D.ZodNullable:return Q0(t,r);case D.ZodOptional:return rw(t,r);case D.ZodMap:return W0(t,r);case D.ZodSet:return sw(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return ow(t,r);case D.ZodNaN:case D.ZodNever:return G0(r);case D.ZodEffects:return U0(t,r);case D.ZodAny:return ze(r);case D.ZodUnknown:return cw(r);case D.ZodDefault:return H0(t,r);case D.ZodBranded:return Uu(t,r);case D.ZodReadonly:return uw(t,r);case D.ZodCatch:return F0(t,r);case D.ZodPipeline:return nw(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function Y(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==N0)return a}if(n&&!r){let a=Lj(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=lw(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&zj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Lj,zj,Ge=S(()=>{zu();bg();Hu();ir();Lj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Fu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ze(e)):e.$refStrategy==="seen"?ze(e):void 0}},zj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var dw=S(()=>{});var xg,vg=S(()=>{Ge();Bh();ir();xg=(t,e)=>{let r=M0(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ze(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ze(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var pw=S(()=>{zu();Bh();jn();Hu();Ge();dw();ir();qh();Vh();Wh();Bu();Kh();Jh();Xh();Yh();Qh();eg();tg();og();sg();ig();ag();cg();ug();lg();dg();pg();mg();_g();Wu();fg();qu();hg();gg();Ku();yg();bg();vg();vg()});function Fj(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Sg(t,e){return nr(t)?uh(t,{target:Fj(e?.target),io:e?.pipeStrategy??"input"}):xg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function kg(t){let r=Nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function wg(t,e){let r=An(t,e);if(!r.success)throw r.error;return r.data}var Eg=S(()=>{ph();oa();pw()});function mw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function fw(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];mw(i)&&mw(s)?r[o]={...i,...s}:r[o]=s}return r}var Hj,Gu,hw=S(()=>{oa();jo();I0();Eg();Hj=6e4,Gu=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler($u,r=>{this._oncancel(r)}),this.setNotificationHandler(Pu,r=>{this._onprogress(r)}),this.setRequestHandler(Tu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ru,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ou,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,m=new B(d.error.code,d.error.message,d.error.data);l(m)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new B(G.InvalidParams,`Task not found: ${s}`);if(!Mn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Mn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Dn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Iu,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new B(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Nu,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(Mn(o.status))throw new B(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new B(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof B?o:new B(G.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),ca(s)||v0(s)?this._onresponse(s):Rh(s)?this._onrequest(s,i):x0(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=B.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Dn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=y0(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(i.signal.aborted)throw new B(G.ConnectionClosed,"Request was cancelled");let h={...m,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let p=h.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:G.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ca(e))n(e);else{let i=new B(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(ca(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),ca(e))o(e);else{let i=B.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof B?i:new B(G.InternalError,String(i))}}return}let s;try{let i=await this.request(e,js,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new B(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Mn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new B(G.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(G.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof B?i:new B(G.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Dn]:c}});let p=_=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));let b=_ instanceof B?_:new B(G.RequestTimeout,String(_));l(b)};this._responseHandlers.set(m,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=An(r,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let f=n?.timeout??Hj,g=()=>p(B.fromError(G.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(m,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let v=this._responseHandlers.get(m);v?v(b):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,_),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(m),l(b)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(m),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Cu,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Au,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},w0,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Dn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Dn]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Dn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=kg(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=wg(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=kg(e);this._notificationHandlers.set(n,o=>{let s=wg(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Rh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new B(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new B(G.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new B(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=ma.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Mn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new B(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Mn(a.status))throw new B(G.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=ma.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Mn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var xa=L(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var _a=class{};he._CodeOrName=_a;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Lo=class extends _a{constructor(e){if(super(),!he.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};he.Name=Lo;var ar=class extends _a{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Lo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ar;he.nil=new ar("");function gw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Tg(r,e[n]),r.push(t[++n]);return new ar(r)}he._=gw;var $g=new ar("+");function yw(t,...e){let r=[ba(t[0])],n=0;for(;n<e.length;)r.push($g),Tg(r,e[n]),r.push($g,ba(t[++n]));return Uj(r),new ar(r)}he.str=yw;function Tg(t,e){e instanceof ar?t.push(...e._items):e instanceof Lo?t.push(e):t.push(qj(e))}he.addCodeArg=Tg;function Uj(t){let e=1;for(;e<t.length-1;){if(t[e]===$g){let r=Bj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Bj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Lo||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Lo))return`"${t}${e.slice(1)}`}function Zj(t,e){return e.emptyStr()?t:t.emptyStr()?e:yw`${t}${e}`}he.strConcat=Zj;function qj(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ba(Array.isArray(t)?t.join(","):t)}function Vj(t){return new ar(ba(t))}he.stringify=Vj;function ba(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=ba;function Wj(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ar(`.${t}`):gw`[${t}]`}he.getProperty=Wj;function Kj(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ar(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=Kj;function Gj(t){return new ar(t.toString())}he.regexpCode=Gj});var Cg=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ValueScope=Dt.ValueScopeName=Dt.Scope=Dt.varKinds=Dt.UsedValueState=void 0;var Nt=xa(),Pg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ju;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ju||(Dt.UsedValueState=Ju={}));Dt.varKinds={const:new Nt.Name("const"),let:new Nt.Name("let"),var:new Nt.Name("var")};var Xu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Nt.Name?e:this.name(e)}name(e){return new Nt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Dt.Scope=Xu;var Yu=class extends Nt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Nt._)`.${new Nt.Name(r)}[${n}]`}};Dt.ValueScopeName=Yu;var Jj=(0,Nt._)`\n`,Rg=class extends Xu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Jj:Nt.nil}}get(){return this._scope}name(e){return new Yu(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Nt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Nt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Ju.Started);let l=r(u);if(l){let d=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const;s=(0,Nt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Nt._)`${s}${l}${this.opts._n}`;else throw new Pg(u);c.set(u,Ju.Completed)})}return s}};Dt.ValueScope=Rg});var oe=L(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.or=se.and=se.not=se.CodeGen=se.operators=se.varKinds=se.ValueScopeName=se.ValueScope=se.Scope=se.Name=se.regexpCode=se.stringify=se.getProperty=se.nil=se.strConcat=se.str=se._=void 0;var pe=xa(),br=Cg(),Ln=xa();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Ln._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Ln.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return Ln.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Ln.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return Ln.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Ln.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return Ln.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Ln.Name}});var rl=Cg();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return rl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return rl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return rl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return rl.varKinds}});se.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var sn=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Og=class extends sn{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?br.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Vs(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},Qu=class extends sn{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return tl(e,this.rhs)}},Ig=class extends Qu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ag=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ng=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Dg=class extends sn{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Mg=class extends sn{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Vs(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},va=class extends sn{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Xj(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ho(e,r.names),{})}},an=class extends va{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},jg=class extends va{},qs=class extends an{};qs.kind="else";var zo=class t extends an{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new qs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(_w(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Vs(this.condition,e,r),this}get names(){let e=super.names;return tl(e,this.condition),this.else&&Ho(e,this.else.names),e}};zo.kind="if";var Fo=class extends an{};Fo.kind="for";var Lg=class extends Fo{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Vs(this.iteration,e,r),this}get names(){return Ho(super.names,this.iteration.names)}},zg=class extends Fo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?br.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=tl(super.names,this.from);return tl(e,this.to)}},el=class extends Fo{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Vs(this.iterable,e,r),this}get names(){return Ho(super.names,this.iterable.names)}},Sa=class extends an{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Sa.kind="func";var ka=class extends va{render(e){return"return "+super.render(e)}};ka.kind="return";var Fg=class extends an{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Ho(e,this.catch.names),this.finally&&Ho(e,this.finally.names),e}},wa=class extends an{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};wa.kind="catch";var Ea=class extends an{render(e){return"finally"+super.render(e)}};Ea.kind="finally";var Hg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
456
+ `:""},this._extScope=e,this._scope=new br.Scope({parent:e}),this._nodes=[new jg]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Og(e,s,n)),s}const(e,r,n){return this._def(br.varKinds.const,e,r,n)}let(e,r,n){return this._def(br.varKinds.let,e,r,n)}var(e,r,n){return this._def(br.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Qu(e,r,n))}add(e,r){return this._leafNode(new Ig(e,se.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new Mg(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,pe.addCodeArg)(r,o));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new zo(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new zo(e))}else(){return this._elseNode(new qs)}endIf(){return this._endBlockNode(zo,qs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Lg(e),r)}forRange(e,r,n,o,s=this.opts.es5?br.varKinds.var:br.varKinds.let){let i=this._scope.toName(e);return this._for(new zg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=br.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),n(s)})}return this._for(new el("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?br.varKinds.var:br.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new el("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Fo)}label(e){return this._leafNode(new Ag(e))}break(e){return this._leafNode(new Ng(e))}return(e){let r=new ka;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ka)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Fg;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new wa(s),r(s)}return n&&(this._currNode=o.finally=new Ea,this.code(n)),this._endBlockNode(wa,Ea)}throw(e){return this._leafNode(new Dg(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=pe.nil,n,o){return this._blockNode(new Sa(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Sa)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof zo))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};se.CodeGen=Hg;function Ho(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function tl(t,e){return e instanceof pe._CodeOrName?Ho(t,e.names):t}function Vs(t,e,r){if(t instanceof pe.Name)return n(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Xj(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function _w(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${Ug(t)}`}se.not=_w;var Yj=bw(se.operators.AND);function Qj(...t){return t.reduce(Yj)}se.and=Qj;var eL=bw(se.operators.OR);function tL(...t){return t.reduce(eL)}se.or=tL;function bw(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${Ug(e)} ${t} ${Ug(r)}`}function Ug(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=L(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.checkStrictMode=ae.getErrorPath=ae.Type=ae.useFunc=ae.setEvaluated=ae.evaluatedPropsToName=ae.mergeEvaluated=ae.eachItem=ae.unescapeJsonPointer=ae.escapeJsonPointer=ae.escapeFragment=ae.unescapeFragment=ae.schemaRefOrVal=ae.schemaHasRulesButRef=ae.schemaHasRules=ae.checkUnknownRules=ae.alwaysValidSchema=ae.toHash=void 0;var Ee=oe(),rL=xa();function nL(t){let e={};for(let r of t)e[r]=!0;return e}ae.toHash=nL;function oL(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Sw(t,e),!kw(e,t.self.RULES.all))}ae.alwaysValidSchema=oL;function Sw(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||$w(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=Sw;function kw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ae.schemaHasRules=kw;function sL(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ae.schemaHasRulesButRef=sL;function iL({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ee._)`${r}`}return(0,Ee._)`${t}${e}${(0,Ee.getProperty)(n)}`}ae.schemaRefOrVal=iL;function aL(t){return ww(decodeURIComponent(t))}ae.unescapeFragment=aL;function cL(t){return encodeURIComponent(Zg(t))}ae.escapeFragment=cL;function Zg(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=Zg;function ww(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=ww;function uL(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ae.eachItem=uL;function xw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ee.Name?(s instanceof Ee.Name?t(o,s,i):e(o,s,i),i):s instanceof Ee.Name?(e(o,i,s),s):r(s,i);return a===Ee.Name&&!(c instanceof Ee.Name)?n(o,c):c}}ae.mergeEvaluated={props:xw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ee._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ee._)`${r} || {}`).code((0,Ee._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ee._)`${r} || {}`),qg(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ew}),items:xw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ee._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ee._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Ew(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ee._)`{}`);return e!==void 0&&qg(t,r,e),r}ae.evaluatedPropsToName=Ew;function qg(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ee._)`${e}${(0,Ee.getProperty)(n)}`,!0))}ae.setEvaluated=qg;var vw={};function lL(t,e){return t.scopeValue("func",{ref:e,code:vw[e.code]||(vw[e.code]=new rL._Code(e.code))})}ae.useFunc=lL;var Bg;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Bg||(ae.Type=Bg={}));function dL(t,e,r){if(t instanceof Ee.Name){let n=e===Bg.Num;return r?n?(0,Ee._)`"[" + ${t} + "]"`:(0,Ee._)`"['" + ${t} + "']"`:n?(0,Ee._)`"/" + ${t}`:(0,Ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ee.getProperty)(t).toString():"/"+Zg(t)}ae.getErrorPath=dL;function $w(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=$w});var cn=L(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var ft=oe(),pL={data:new ft.Name("data"),valCxt:new ft.Name("valCxt"),instancePath:new ft.Name("instancePath"),parentData:new ft.Name("parentData"),parentDataProperty:new ft.Name("parentDataProperty"),rootData:new ft.Name("rootData"),dynamicAnchors:new ft.Name("dynamicAnchors"),vErrors:new ft.Name("vErrors"),errors:new ft.Name("errors"),this:new ft.Name("this"),self:new ft.Name("self"),scope:new ft.Name("scope"),json:new ft.Name("json"),jsonPos:new ft.Name("jsonPos"),jsonLen:new ft.Name("jsonLen"),jsonPart:new ft.Name("jsonPart")};Vg.default=pL});var $a=L(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.extendErrors=ht.resetErrorsCount=ht.reportExtraError=ht.reportError=ht.keyword$DataError=ht.keywordError=void 0;var fe=oe(),nl=me(),$t=cn();ht.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ht.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function mL(t,e=ht.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Rw(t,e,r);n??(i||a)?Tw(s,c):Pw(o,(0,fe._)`[${c}]`)}ht.reportError=mL;function fL(t,e=ht.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Rw(t,e,r);Tw(o,a),s||i||Pw(n,$t.default.vErrors)}ht.reportExtraError=fL;function hL(t,e){t.assign($t.default.errors,e),t.if((0,fe._)`${$t.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${$t.default.vErrors}.length`,e),()=>t.assign($t.default.vErrors,null)))}ht.resetErrorsCount=hL;function gL({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,$t.default.errors,a=>{t.const(i,(0,fe._)`${$t.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)($t.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}ht.extendErrors=gL;function Tw(t,e){let r=t.const("err",e);t.if((0,fe._)`${$t.default.vErrors} === null`,()=>t.assign($t.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${$t.default.vErrors}.push(${r})`),t.code((0,fe._)`${$t.default.errors}++`)}function Pw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var Uo={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function Rw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:yL(t,e,r)}function yL(t,e,r={}){let{gen:n,it:o}=t,s=[_L(o,r),bL(t,r)];return xL(t,e,s),n.object(...s)}function _L({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,nl.getErrorPath)(e,nl.Type.Str)}`:t;return[$t.default.instancePath,(0,fe.strConcat)($t.default.instancePath,r)]}function bL({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,fe.str)`${e}/${t}`;return r&&(o=(0,fe.str)`${o}${(0,nl.getErrorPath)(r,nl.Type.Str)}`),[Uo.schemaPath,o]}function xL(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Uo.keyword,o],[Uo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([Uo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Uo.schema,i],[Uo.parentSchema,(0,fe._)`${l}${d}`],[$t.default.data,s]),u&&n.push([Uo.propertyName,u])}});var Ow=L(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.boolOrEmptySchema=Ws.topBoolOrEmptySchema=void 0;var vL=$a(),SL=oe(),kL=cn(),wL={message:"boolean schema is false"};function EL(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Cw(t,!1):typeof r=="object"&&r.$async===!0?e.return(kL.default.data):(e.assign((0,SL._)`${n}.errors`,null),e.return(!0))}Ws.topBoolOrEmptySchema=EL;function $L(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Cw(t)):r.var(e,!0)}Ws.boolOrEmptySchema=$L;function Cw(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,vL.reportError)(o,wL,void 0,e)}});var Wg=L(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getRules=Ks.isJSONType=void 0;var TL=["string","number","integer","boolean","null","object","array"],PL=new Set(TL);function RL(t){return typeof t=="string"&&PL.has(t)}Ks.isJSONType=RL;function CL(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ks.getRules=CL});var Kg=L(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.shouldUseRule=zn.shouldUseGroup=zn.schemaHasRulesForType=void 0;function OL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Iw(t,n)}zn.schemaHasRulesForType=OL;function Iw(t,e){return e.rules.some(r=>Aw(t,r))}zn.shouldUseGroup=Iw;function Aw(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}zn.shouldUseRule=Aw});var Ta=L(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reportTypeError=gt.checkDataTypes=gt.checkDataType=gt.coerceAndCheckDataType=gt.getJSONTypes=gt.getSchemaTypes=gt.DataType=void 0;var IL=Wg(),AL=Kg(),NL=$a(),re=oe(),Nw=me(),Gs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gs||(gt.DataType=Gs={}));function DL(t){let e=Dw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}gt.getSchemaTypes=DL;function Dw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(IL.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}gt.getJSONTypes=Dw;function ML(t,e){let{gen:r,data:n,opts:o}=t,s=jL(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,AL.schemaHasRulesForType)(t,e[0]));if(i){let a=Jg(e,n,o.strictNumbers,Gs.Wrong);r.if(a,()=>{s.length?LL(t,e,s):Xg(t)})}return i}gt.coerceAndCheckDataType=ML;var Mw=new Set(["string","number","integer","boolean","null"]);function jL(t,e){return e?t.filter(r=>Mw.has(r)||e==="array"&&r==="array"):[]}function LL(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,re._)`typeof ${o}`),a=n.let("coerced",(0,re._)`undefined`);s.coerceTypes==="array"&&n.if((0,re._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,re._)`${o}[0]`).assign(i,(0,re._)`typeof ${o}`).if(Jg(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,re._)`${a} !== undefined`);for(let u of r)(Mw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Xg(t),n.endIf(),n.if((0,re._)`${a} !== undefined`,()=>{n.assign(o,a),zL(t,a)});function c(u){switch(u){case"string":n.elseIf((0,re._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,re._)`"" + ${o}`).elseIf((0,re._)`${o} === null`).assign(a,(0,re._)`""`);return;case"number":n.elseIf((0,re._)`${i} == "boolean" || ${o} === null
457
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,re._)`+${o}`);return;case"integer":n.elseIf((0,re._)`${i} === "boolean" || ${o} === null
458
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,re._)`+${o}`);return;case"boolean":n.elseIf((0,re._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,re._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,re._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,re._)`${i} === "string" || ${i} === "number"
459
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,re._)`[${o}]`)}}}function zL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,re._)`${e} !== undefined`,()=>t.assign((0,re._)`${e}[${r}]`,n))}function Gg(t,e,r,n=Gs.Correct){let o=n===Gs.Correct?re.operators.EQ:re.operators.NEQ,s;switch(t){case"null":return(0,re._)`${e} ${o} null`;case"array":s=(0,re._)`Array.isArray(${e})`;break;case"object":s=(0,re._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,re._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,re._)`typeof ${e} ${o} ${t}`}return n===Gs.Correct?s:(0,re.not)(s);function i(a=re.nil){return(0,re.and)((0,re._)`typeof ${e} == "number"`,a,r?(0,re._)`isFinite(${e})`:re.nil)}}gt.checkDataType=Gg;function Jg(t,e,r,n){if(t.length===1)return Gg(t[0],e,r,n);let o,s=(0,Nw.toHash)(t);if(s.array&&s.object){let i=(0,re._)`typeof ${e} != "object"`;o=s.null?i:(0,re._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=re.nil;s.number&&delete s.integer;for(let i in s)o=(0,re.and)(o,Gg(i,e,r,n));return o}gt.checkDataTypes=Jg;var FL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,re._)`{type: ${t}}`:(0,re._)`{type: ${e}}`};function Xg(t){let e=HL(t);(0,NL.reportError)(e,FL)}gt.reportTypeError=Xg;function HL(t){let{gen:e,data:r,schema:n}=t,o=(0,Nw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Lw=L(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});ol.assignDefaults=void 0;var Js=oe(),UL=me();function BL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)jw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>jw(t,s,o.default))}ol.assignDefaults=BL;function jw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Js._)`${s}${(0,Js.getProperty)(e)}`;if(o){(0,UL.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Js._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Js._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Js._)`${a} = ${(0,Js.stringify)(r)}`)}});var cr=L(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.validateUnion=Se.validateArray=Se.usePattern=Se.callValidateCode=Se.schemaProperties=Se.allSchemaProperties=Se.noPropertyInData=Se.propertyInData=Se.isOwnProperty=Se.hasPropFunc=Se.reportMissingProp=Se.checkMissingProp=Se.checkReportMissingProp=void 0;var Ae=oe(),Yg=me(),Fn=cn(),ZL=me();function qL(t,e){let{gen:r,data:n,it:o}=t;r.if(ey(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ae._)`${e}`},!0),t.error()})}Se.checkReportMissingProp=qL;function VL({gen:t,data:e,it:{opts:r}},n,o){return(0,Ae.or)(...n.map(s=>(0,Ae.and)(ey(t,e,s,r.ownProperties),(0,Ae._)`${o} = ${s}`)))}Se.checkMissingProp=VL;function WL(t,e){t.setParams({missingProperty:e},!0),t.error()}Se.reportMissingProp=WL;function zw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ae._)`Object.prototype.hasOwnProperty`})}Se.hasPropFunc=zw;function Qg(t,e,r){return(0,Ae._)`${zw(t)}.call(${e}, ${r})`}Se.isOwnProperty=Qg;function KL(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} !== undefined`;return n?(0,Ae._)`${o} && ${Qg(t,e,r)}`:o}Se.propertyInData=KL;function ey(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} === undefined`;return n?(0,Ae.or)(o,(0,Ae.not)(Qg(t,e,r))):o}Se.noPropertyInData=ey;function Fw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Se.allSchemaProperties=Fw;function GL(t,e){return Fw(e).filter(r=>!(0,Yg.alwaysValidSchema)(t,e[r]))}Se.schemaProperties=GL;function JL({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ae._)`${t}, ${e}, ${n}${o}`:e,d=[[Fn.default.instancePath,(0,Ae.strConcat)(Fn.default.instancePath,s)],[Fn.default.parentData,i.parentData],[Fn.default.parentDataProperty,i.parentDataProperty],[Fn.default.rootData,Fn.default.rootData]];i.opts.dynamicRef&&d.push([Fn.default.dynamicAnchors,Fn.default.dynamicAnchors]);let m=(0,Ae._)`${l}, ${r.object(...d)}`;return c!==Ae.nil?(0,Ae._)`${a}.call(${c}, ${m})`:(0,Ae._)`${a}(${m})`}Se.callValidateCode=JL;var XL=(0,Ae._)`new RegExp`;function YL({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ae._)`${o.code==="new RegExp"?XL:(0,ZL.useFunc)(t,o)}(${r}, ${n})`})}Se.usePattern=YL;function QL(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Ae._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Yg.Type.Num},s),e.if((0,Ae.not)(s),a)})}}Se.validateArray=QL;function ez(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Yg.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ae._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ae.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Se.validateUnion=ez});var Bw=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.validateKeywordUsage=zr.validSchemaType=zr.funcKeywordCode=zr.macroKeywordCode=void 0;var Tt=oe(),Bo=cn(),tz=cr(),rz=$a();function nz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Uw(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Tt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}zr.macroKeywordCode=nz;function oz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;iz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Uw(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)f(),e.modifying&&Hw(t),g(()=>t.error());else{let y=e.async?h():p();e.modifying&&Hw(t),g(()=>sz(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,Tt._)`await `),_=>n.assign(d,!1).if((0,Tt._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,Tt._)`${_}.errors`),()=>n.throw(_))),y}function p(){let y=(0,Tt._)`${l}.errors`;return n.assign(y,null),f(Tt.nil),y}function f(y=e.async?(0,Tt._)`await `:Tt.nil){let _=c.opts.passContext?Bo.default.this:Bo.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Tt._)`${y}${(0,tz.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;n.if((0,Tt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}zr.funcKeywordCode=oz;function Hw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Tt._)`${n.parentData}[${n.parentDataProperty}]`))}function sz(t,e){let{gen:r}=t;r.if((0,Tt._)`Array.isArray(${e})`,()=>{r.assign(Bo.default.vErrors,(0,Tt._)`${Bo.default.vErrors} === null ? ${e} : ${Bo.default.vErrors}.concat(${e})`).assign(Bo.default.errors,(0,Tt._)`${Bo.default.vErrors}.length`),(0,rz.extendErrors)(t)},()=>t.error())}function iz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Uw(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Tt.stringify)(r)})}function az(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}zr.validSchemaType=az;function cz({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}zr.validateKeywordUsage=cz});var qw=L(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.extendSubschemaMode=Hn.extendSubschemaData=Hn.getSubschema=void 0;var Fr=oe(),Zw=me();function uz(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}${(0,Fr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Zw.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Hn.getSubschema=uz;function lz(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,m=a.let("data",(0,Fr._)`${e.data}${(0,Fr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Fr.str)`${u}${(0,Zw.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Fr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Fr.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Hn.extendSubschemaData=lz;function dz(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Hn.extendSubschemaMode=dz});var ty=L((BG,Vw)=>{"use strict";Vw.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Kw=L((ZG,Ww)=>{"use strict";var Un=Ww.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};sl(e,n,o,t,"",t)};Un.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Un.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Un.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Un.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function sl(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Un.arrayKeywords)for(var m=0;m<d.length;m++)sl(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in Un.propsKeywords){if(d&&typeof d=="object")for(var h in d)sl(t,e,r,d[h],o+"/"+l+"/"+pz(h),s,o,l,n,h)}else(l in Un.keywords||t.allKeys&&!(l in Un.skipKeywords))&&sl(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function pz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Pa=L(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getSchemaRefs=Mt.resolveUrl=Mt.normalizeId=Mt._getFullPath=Mt.getFullPath=Mt.inlineRef=void 0;var mz=me(),fz=ty(),hz=Kw(),gz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function yz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!ry(t):e?Gw(t)<=e:!1}Mt.inlineRef=yz;var _z=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ry(t){for(let e in t){if(_z.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(ry)||typeof r=="object"&&ry(r))return!0}return!1}function Gw(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!gz.has(r)&&(typeof t[r]=="object"&&(0,mz.eachItem)(t[r],n=>e+=Gw(n)),e===1/0))return 1/0}return e}function Jw(t,e="",r){r!==!1&&(e=Xs(e));let n=t.parse(e);return Xw(t,n)}Mt.getFullPath=Jw;function Xw(t,e){return t.serialize(e).split("#")[0]+"#"}Mt._getFullPath=Xw;var bz=/#\/?$/;function Xs(t){return t?t.replace(bz,""):""}Mt.normalizeId=Xs;function xz(t,e,r){return r=Xs(r),t.resolve(e,r)}Mt.resolveUrl=xz;var vz=/^[a-z_][-a-z0-9._]*$/i;function Sz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xs(t[r]||e),s={"":o},i=Jw(n,o,!1),a={},c=new Set;return hz(t,{allKeys:!0},(d,m,h,p)=>{if(p===void 0)return;let f=i+m,g=s[p];typeof d[r]=="string"&&(g=y.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[m]=g;function y(b){let v=this.opts.uriResolver.resolve;if(b=Xs(g?v(g,b):b),c.has(b))throw l(b);c.add(b);let E=this.refs[b];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,b):b!==Xs(f)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=f),b}function _(b){if(typeof b=="string"){if(!vz.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,m,h){if(m!==void 0&&!fz(d,m))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Mt.getSchemaRefs=Sz});var Oa=L(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getData=Bn.KeywordCxt=Bn.validateFunctionCode=void 0;var rE=Ow(),Yw=Ta(),oy=Kg(),il=Ta(),kz=Lw(),Ca=Bw(),ny=qw(),V=oe(),ee=cn(),wz=Pa(),un=me(),Ra=$a();function Ez(t){if(sE(t)&&(iE(t),oE(t))){Pz(t);return}nE(t,()=>(0,rE.topBoolOrEmptySchema)(t))}Bn.validateFunctionCode=Ez;function nE({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,V._)`"use strict"; ${Qw(r,o)}`),Tz(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${$z(o)}`,n.$async,()=>t.code(Qw(r,o)).code(s))}function $z(t){return(0,V._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,V._)`, ${ee.default.dynamicAnchors}={}`:V.nil}}={}`}function Tz(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,V._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,V._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,V._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,V._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,V._)`""`),t.var(ee.default.parentData,(0,V._)`undefined`),t.var(ee.default.parentDataProperty,(0,V._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`{}`)})}function Pz(t){let{schema:e,opts:r,gen:n}=t;nE(t,()=>{r.$comment&&e.$comment&&cE(t),Az(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&Rz(t),aE(t),Mz(t)})}function Rz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,V._)`${r}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function Qw(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${r} */`:V.nil}function Cz(t,e){if(sE(t)&&(iE(t),oE(t))){Oz(t,e);return}(0,rE.boolOrEmptySchema)(t,e)}function oE({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function sE(t){return typeof t.schema!="boolean"}function Oz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&cE(t),Nz(t),Dz(t);let s=n.const("_errs",ee.default.errors);aE(t,s),n.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function iE(t){(0,un.checkUnknownRules)(t),Iz(t)}function aE(t,e){if(t.opts.jtd)return eE(t,[],!1,e);let r=(0,Yw.getSchemaTypes)(t.schema),n=(0,Yw.coerceAndCheckDataType)(t,r);eE(t,r,!n,e)}function Iz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,un.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Az(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,un.checkStrictMode)(t,"default is ignored in the schema root")}function Nz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,wz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Dz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function cE({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,V._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Mz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,V._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,V._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,V._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&jz(t),e.return((0,V._)`${ee.default.errors} === 0`))}function jz({gen:t,evaluated:e,props:r,items:n}){r instanceof V.Name&&t.assign((0,V._)`${e}.props`,r),n instanceof V.Name&&t.assign((0,V._)`${e}.items`,n)}function eE(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,un.schemaHasRulesButRef)(s,l))){o.block(()=>lE(t,"$ref",l.all.$ref.definition));return}c.jtd||Lz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,oy.shouldUseGroup)(s,m)&&(m.type?(o.if((0,il.checkDataType)(m.type,i,c.strictNumbers)),tE(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,il.reportTypeError)(t)),o.endIf()):tE(t,m),a||o.if((0,V._)`${ee.default.errors} === ${n||0}`))}}function tE(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,kz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,oy.shouldUseRule)(n,s)&&lE(t,s.keyword,s.definition,e.type)})}function Lz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(zz(t,e),t.opts.allowUnionTypes||Fz(t,e),Hz(t,t.dataTypes))}function zz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{uE(t.dataTypes,r)||sy(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Bz(t,e)}}function Fz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&sy(t,"use allowUnionTypes to allow union type keyword")}function Hz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,oy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Uz(e,i))&&sy(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Uz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function uE(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Bz(t,e){let r=[];for(let n of t.dataTypes)uE(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function sy(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,un.checkStrictMode)(t,e,t.opts.strictTypes)}var al=class{constructor(e,r,n){if((0,Ca.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,un.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",dE(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ca.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,r,n){this.failResult((0,V.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,V.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,V._)`${r} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Ra.reportExtraError:Ra.reportError)(this,this.def.error,r)}$dataError(){(0,Ra.reportError)(this,this.def.$dataError||Ra.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ra.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=V.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=V.nil,r=V.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,V.or)((0,V._)`${o} === undefined`,r)),e!==V.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(n.length){if(!(r instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,V._)`${(0,il.checkDataTypes)(c,r,s.opts.strictNumbers,il.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${r})`}return V.nil}}subschema(e,r){let n=(0,ny.getSubschema)(this.it,e);(0,ny.extendSubschemaData)(n,this.it,e),(0,ny.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Cz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=un.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=un.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,V.Name)),!0}};Bn.KeywordCxt=al;function lE(t,e,r,n){let o=new al(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ca.funcKeywordCode)(o,r):"macro"in r?(0,Ca.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ca.funcKeywordCode)(o,r)}var Zz=/^\/(?:[^~]|~0|~1)*$/,qz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dE(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!Zz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=qz.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,V._)`${s}${(0,V.getProperty)((0,un.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Bn.getData=dE});var cl=L(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});var iy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ay.default=iy});var Ia=L(ly=>{"use strict";Object.defineProperty(ly,"__esModule",{value:!0});var cy=Pa(),uy=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,cy.resolveUrl)(e,r,n),this.missingSchema=(0,cy.normalizeId)((0,cy.getFullPath)(e,this.missingRef))}};ly.default=uy});var ll=L(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;var xr=oe(),Vz=cl(),Zo=cn(),vr=Pa(),pE=me(),Wz=Oa(),Ys=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,vr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ur.SchemaEnv=Ys;function py(t){let e=mE.call(this,t);if(e)return e;let r=(0,vr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new xr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Vz.default,code:(0,xr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Zo.default.data,parentData:Zo.default.parentData,parentDataProperty:Zo.default.parentDataProperty,dataNames:[Zo.default.data],dataPathArr:[xr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,xr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:xr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xr._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Wz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Zo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${Zo.default.self}`,`${Zo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:f}=u;h.evaluated={props:p instanceof xr.Name?void 0:p,items:f instanceof xr.Name?void 0:f,dynamicProps:p instanceof xr.Name,dynamicItems:f instanceof xr.Name},h.source&&(h.source.evaluated=(0,xr.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}ur.compileSchema=py;function Kz(t,e,r){var n;r=(0,vr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Xz.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Ys({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Gz.call(this,s)}ur.resolveRef=Kz;function Gz(t){return(0,vr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:py.call(this,t)}function mE(t){for(let e of this._compilations)if(Jz(e,t))return e}ur.getCompilingSchema=mE;function Jz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Xz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ul.call(this,t,e)}function ul(t,e){let r=this.opts.uriResolver.parse(e),n=(0,vr._getFullPath)(this.opts.uriResolver,r),o=(0,vr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return dy.call(this,r,t);let s=(0,vr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ul.call(this,t,i);return typeof a?.schema!="object"?void 0:dy.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||py.call(this,i),s===(0,vr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,vr.resolveUrl)(this.opts.uriResolver,o,u)),new Ys({schema:a,schemaId:c,root:t,baseId:o})}return dy.call(this,r,i)}}ur.resolveSchema=ul;var Yz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function dy(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,pE.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Yz.has(a)&&u&&(e=(0,vr.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,pE.schemaHasRulesButRef)(r,this.RULES)){let a=(0,vr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ul.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ys({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var fE=L((JG,Qz)=>{Qz.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var fy=L((XG,_E)=>{"use strict";var eF=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),gE=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function my(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var tF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function hE(t){return t.length=0,!0}function rF(t,e,r){if(t.length){let n=my(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function nF(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=rF;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=hE}else{o.push(u);continue}}return o.length&&(a===hE?r.zone=o.join(""):i?n.push(o.join("")):n.push(my(o))),r.address=n.join(""),r}function yE(t){if(oF(t,":")<2)return{host:t,isIPV6:!1};let e=nF(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function oF(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function sF(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function iF(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function aF(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!gE(r)){let n=yE(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}_E.exports={nonSimpleDomain:tF,recomposeAuthority:aF,normalizeComponentEncoding:iF,removeDotSegments:sF,isIPv4:gE,isUUID:eF,normalizeIPv6:yE,stringArrayToHexStripped:my}});var kE=L((YG,SE)=>{"use strict";var{isUUID:cF}=fy(),uF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,lF=["http","https","ws","wss","urn","urn:uuid"];function dF(t){return lF.indexOf(t)!==-1}function hy(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function bE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function xE(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function pF(t){return t.secure=hy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function mF(t){if((t.port===(hy(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function fF(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(uF);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=gy(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function hF(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=gy(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function gF(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!cF(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function yF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var vE={scheme:"http",domainHost:!0,parse:bE,serialize:xE},_F={scheme:"https",domainHost:vE.domainHost,parse:bE,serialize:xE},dl={scheme:"ws",domainHost:!0,parse:pF,serialize:mF},bF={scheme:"wss",domainHost:dl.domainHost,parse:dl.parse,serialize:dl.serialize},xF={scheme:"urn",parse:fF,serialize:hF,skipNormalize:!0},vF={scheme:"urn:uuid",parse:gF,serialize:yF,skipNormalize:!0},pl={http:vE,https:_F,ws:dl,wss:bF,urn:xF,"urn:uuid":vF};Object.setPrototypeOf(pl,null);function gy(t){return t&&(pl[t]||pl[t.toLowerCase()])||void 0}SE.exports={wsIsSecure:hy,SCHEMES:pl,isValidSchemeName:dF,getSchemeHandler:gy}});var $E=L((QG,fl)=>{"use strict";var{normalizeIPv6:SF,removeDotSegments:Aa,recomposeAuthority:kF,normalizeComponentEncoding:ml,isIPv4:wF,nonSimpleDomain:EF}=fy(),{SCHEMES:$F,getSchemeHandler:wE}=kE();function TF(t,e){return typeof t=="string"?t=Hr(ln(t,e),e):typeof t=="object"&&(t=ln(Hr(t,e),e)),t}function PF(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=EE(ln(t,n),ln(e,n),n,!0);return n.skipEscape=!0,Hr(o,n)}function EE(t,e,r,n){let o={};return n||(t=ln(Hr(t,r),r),e=ln(Hr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Aa(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Aa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Aa(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Aa(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function RF(t,e,r){return typeof t=="string"?(t=unescape(t),t=Hr(ml(ln(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Hr(ml(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Hr(ml(ln(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Hr(ml(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Hr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=wE(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=kF(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Aa(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var CF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ln(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(CF);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(wF(n.host)===!1){let c=SF(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=wE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&EF(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var yy={SCHEMES:$F,normalize:TF,resolve:PF,resolveComponent:EE,equal:RF,serialize:Hr,parse:ln};fl.exports=yy;fl.exports.default=yy;fl.exports.fastUri=yy});var PE=L(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});var TE=$E();TE.code='require("ajv/dist/runtime/uri").default';_y.default=TE});var ME=L(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.CodeGen=ut.Name=ut.nil=ut.stringify=ut.str=ut._=ut.KeywordCxt=void 0;var OF=Oa();Object.defineProperty(ut,"KeywordCxt",{enumerable:!0,get:function(){return OF.KeywordCxt}});var Qs=oe();Object.defineProperty(ut,"_",{enumerable:!0,get:function(){return Qs._}});Object.defineProperty(ut,"str",{enumerable:!0,get:function(){return Qs.str}});Object.defineProperty(ut,"stringify",{enumerable:!0,get:function(){return Qs.stringify}});Object.defineProperty(ut,"nil",{enumerable:!0,get:function(){return Qs.nil}});Object.defineProperty(ut,"Name",{enumerable:!0,get:function(){return Qs.Name}});Object.defineProperty(ut,"CodeGen",{enumerable:!0,get:function(){return Qs.CodeGen}});var IF=cl(),AE=Ia(),AF=Wg(),Na=ll(),NF=oe(),Da=Pa(),hl=Ta(),xy=me(),RE=fE(),DF=PE(),NE=(t,e)=>new RegExp(t,e);NE.code="new RegExp";var MF=["removeAdditional","useDefaults","coerceTypes"],jF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),LF={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},zF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},CE=200;function FF(t){var e,r,n,o,s,i,a,c,u,l,d,m,h,p,f,g,y,_,b,v,E,C,x,k,P;let N=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,O=R===!0||R===void 0?1:R||0,F=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:NE,K=(o=t.uriResolver)!==null&&o!==void 0?o:DF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:N)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:N)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:N)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:N)!==null&&m!==void 0?m:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:N)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:O,regExp:F}:{optimize:O,regExp:F},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:CE,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:CE,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(v=t.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(x=t.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(k=t.unicodeRegExp)!==null&&k!==void 0?k:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:K}}var Ma=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...FF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new NF.ValueScope({scope:{},prefixes:jF,es5:r,lines:n}),this.logger=VF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,AF.getRules)(),OE.call(this,LF,e,"NOT SUPPORTED"),OE.call(this,zF,e,"DEPRECATED","warn"),this._metaOpts=ZF.call(this),e.formats&&UF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&BF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),HF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=RE;n==="id"&&(o={...RE},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let m=this._addSchema(l,d);return m.validate||i.call(this,m)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof AE.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Da.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=IE.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Na.SchemaEnv({schema:{},schemaId:n});if(r=Na.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=IE.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Da.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(KF.call(this,n,r),!r)return(0,xy.eachItem)(n,s=>by.call(this,s)),this;JF.call(this,r);let o={...r,type:(0,hl.getJSONTypes)(r.type),schemaType:(0,hl.getJSONTypes)(r.schemaType)};return(0,xy.eachItem)(n,o.type.length===0?s=>by.call(this,s,o):s=>o.type.forEach(i=>by.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=DE(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Da.normalizeId)(i||n);let u=Da.getSchemaRefs.call(this,e,n);return c=new Na.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Na.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Na.compileSchema.call(this,e)}finally{this.opts=r}}};Ma.ValidationError=IF.default;Ma.MissingRefError=AE.default;ut.default=Ma;function OE(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function IE(t){return t=(0,Da.normalizeId)(t),this.schemas[t]||this.refs[t]}function HF(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function UF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function BF(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function ZF(){let t={...this.opts};for(let e of MF)delete t[e];return t}var qF={log(){},warn(){},error(){}};function VF(t){if(t===!1)return qF;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var WF=/^[a-z_$][a-z0-9_$:-]*$/i;function KF(t,e){let{RULES:r}=this;if((0,xy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!WF.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function by(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,hl.getJSONTypes)(e.type),schemaType:(0,hl.getJSONTypes)(e.schemaType)}};e.before?GF.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function GF(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function JF(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=DE(e)),t.validateSchema=this.compile(e,!0))}var XF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function DE(t){return{anyOf:[t,XF]}}});var jE=L(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});var YF={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vy.default=YF});var HE=L(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.callRef=qo.getValidate=void 0;var QF=Ia(),LE=cr(),jt=oe(),ei=cn(),zE=ll(),gl=me(),eH={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=zE.resolveRef.call(c,u,o,r);if(l===void 0)throw new QF.default(n.opts.uriResolver,o,r);if(l instanceof zE.SchemaEnv)return m(l);return h(l);function d(){if(s===u)return yl(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return yl(t,(0,jt._)`${p}.validate`,u,u.$async)}function m(p){let f=FE(t,p);yl(t,f,p,p.$async)}function h(p){let f=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,jt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:jt.nil,topSchemaRef:f,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function FE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,jt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}qo.getValidate=FE;function yl(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ei.default.this:jt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,jt._)`await ${(0,LE.callValidateCode)(t,e,u)}`),h(e),i||o.assign(p,!0)},f=>{o.if((0,jt._)`!(${f} instanceof ${s.ValidationError})`,()=>o.throw(f)),m(f),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,LE.callValidateCode)(t,e,u),()=>h(e),()=>m(e))}function m(p){let f=(0,jt._)`${p}.errors`;o.assign(ei.default.vErrors,(0,jt._)`${ei.default.vErrors} === null ? ${f} : ${ei.default.vErrors}.concat(${f})`),o.assign(ei.default.errors,(0,jt._)`${ei.default.vErrors}.length`)}function h(p){var f;if(!s.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=gl.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,jt._)`${p}.evaluated.props`);s.props=gl.mergeEvaluated.props(o,y,s.props,jt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=gl.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,jt._)`${p}.evaluated.items`);s.items=gl.mergeEvaluated.items(o,y,s.items,jt.Name)}}}qo.callRef=yl;qo.default=eH});var UE=L(Sy=>{"use strict";Object.defineProperty(Sy,"__esModule",{value:!0});var tH=jE(),rH=HE(),nH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",tH.default,rH.default];Sy.default=nH});var BE=L(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var _l=oe(),Zn=_l.operators,bl={maximum:{okStr:"<=",ok:Zn.LTE,fail:Zn.GT},minimum:{okStr:">=",ok:Zn.GTE,fail:Zn.LT},exclusiveMaximum:{okStr:"<",ok:Zn.LT,fail:Zn.GTE},exclusiveMinimum:{okStr:">",ok:Zn.GT,fail:Zn.LTE}},oH={message:({keyword:t,schemaCode:e})=>(0,_l.str)`must be ${bl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,_l._)`{comparison: ${bl[t].okStr}, limit: ${e}}`},sH={keyword:Object.keys(bl),type:"number",schemaType:"number",$data:!0,error:oH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,_l._)`${r} ${bl[e].fail} ${n} || isNaN(${r})`)}};ky.default=sH});var ZE=L(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var ja=oe(),iH={message:({schemaCode:t})=>(0,ja.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ja._)`{multipleOf: ${t}}`},aH={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:iH,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ja._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ja._)`${i} !== parseInt(${i})`;t.fail$data((0,ja._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wy.default=aH});var VE=L(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});function qE(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Ey.default=qE;qE.code='require("ajv/dist/runtime/ucs2length").default'});var WE=L($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});var Vo=oe(),cH=me(),uH=VE(),lH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Vo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Vo._)`{limit: ${t}}`},dH={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:lH,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Vo.operators.GT:Vo.operators.LT,i=o.opts.unicode===!1?(0,Vo._)`${r}.length`:(0,Vo._)`${(0,cH.useFunc)(t.gen,uH.default)}(${r})`;t.fail$data((0,Vo._)`${i} ${s} ${n}`)}};$y.default=dH});var KE=L(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});var pH=cr(),mH=me(),ti=oe(),fH={message:({schemaCode:t})=>(0,ti.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ti._)`{pattern: ${t}}`},hH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:fH,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ti._)`new RegExp`:(0,mH.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ti._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,ti._)`!${l}`)}else{let c=(0,pH.usePattern)(t,o);t.fail$data((0,ti._)`!${c}.test(${r})`)}}};Ty.default=hH});var GE=L(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var La=oe(),gH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,La.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,La._)`{limit: ${t}}`},yH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:gH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?La.operators.GT:La.operators.LT;t.fail$data((0,La._)`Object.keys(${r}).length ${o} ${n}`)}};Py.default=yH});var JE=L(Ry=>{"use strict";Object.defineProperty(Ry,"__esModule",{value:!0});var za=cr(),Fa=oe(),_H=me(),bH={message:({params:{missingProperty:t}})=>(0,Fa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Fa._)`{missingProperty: ${t}}`},xH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:bH,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let f of r)if(h?.[f]===void 0&&!p.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,_H.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Fa.nil,d);else for(let h of r)(0,za.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>m(h,p)),t.ok(p)}else e.if((0,za.checkMissingProp)(t,r,h)),(0,za.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,za.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function m(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,za.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Fa.not)(p),()=>{t.error(),e.break()})},Fa.nil)}}};Ry.default=xH});var XE=L(Cy=>{"use strict";Object.defineProperty(Cy,"__esModule",{value:!0});var Ha=oe(),vH={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ha.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ha._)`{limit: ${t}}`},SH={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:vH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ha.operators.GT:Ha.operators.LT;t.fail$data((0,Ha._)`${r}.length ${o} ${n}`)}};Cy.default=SH});var xl=L(Oy=>{"use strict";Object.defineProperty(Oy,"__esModule",{value:!0});var YE=ty();YE.code='require("ajv/dist/runtime/equal").default';Oy.default=YE});var QE=L(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var Iy=Ta(),lt=oe(),kH=me(),wH=xl(),EH={message:({params:{i:t,j:e}})=>(0,lt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,lt._)`{i: ${t}, j: ${e}}`},$H={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:EH,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Iy.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,lt._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,lt._)`${r}.length`),f=e.let("j");t.setParams({i:p,j:f}),e.assign(c,!0),e.if((0,lt._)`${p} > 1`,()=>(d()?m:h)(p,f))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,f){let g=e.name("item"),y=(0,Iy.checkDataTypes)(u,g,a.opts.strictNumbers,Iy.DataType.Wrong),_=e.const("indices",(0,lt._)`{}`);e.for((0,lt._)`;${p}--;`,()=>{e.let(g,(0,lt._)`${r}[${p}]`),e.if(y,(0,lt._)`continue`),u.length>1&&e.if((0,lt._)`typeof ${g} == "string"`,(0,lt._)`${g} += "_"`),e.if((0,lt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(f,(0,lt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,lt._)`${_}[${g}] = ${p}`)})}function h(p,f){let g=(0,kH.useFunc)(e,wH.default),y=e.name("outer");e.label(y).for((0,lt._)`;${p}--;`,()=>e.for((0,lt._)`${f} = ${p}; ${f}--;`,()=>e.if((0,lt._)`${g}(${r}[${p}], ${r}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Ay.default=$H});var e$=L(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Ny=oe(),TH=me(),PH=xl(),RH={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ny._)`{allowedValue: ${t}}`},CH={keyword:"const",$data:!0,error:RH,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ny._)`!${(0,TH.useFunc)(e,PH.default)}(${r}, ${o})`):t.fail((0,Ny._)`${s} !== ${r}`)}};Dy.default=CH});var t$=L(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});var Ua=oe(),OH=me(),IH=xl(),AH={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ua._)`{allowedValues: ${t}}`},NH={keyword:"enum",schemaType:"array",$data:!0,error:AH,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,OH.useFunc)(e,IH.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);l=(0,Ua.or)(...o.map((p,f)=>m(h,f)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,h=>e.if((0,Ua._)`${u()}(${r}, ${h})`,()=>e.assign(l,!0).break()))}function m(h,p){let f=o[p];return typeof f=="object"&&f!==null?(0,Ua._)`${u()}(${r}, ${h}[${p}])`:(0,Ua._)`${r} === ${f}`}}};My.default=NH});var r$=L(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});var DH=BE(),MH=ZE(),jH=WE(),LH=KE(),zH=GE(),FH=JE(),HH=XE(),UH=QE(),BH=e$(),ZH=t$(),qH=[DH.default,MH.default,jH.default,LH.default,zH.default,FH.default,HH.default,UH.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},BH.default,ZH.default];jy.default=qH});var zy=L(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.validateAdditionalItems=void 0;var Wo=oe(),Ly=me(),VH={message:({params:{len:t}})=>(0,Wo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wo._)`{limit: ${t}}`},WH={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:VH,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ly.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}n$(t,n)}};function n$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Wo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Wo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ly.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Wo._)`${a} <= ${e.length}`);r.if((0,Wo.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Ly.Type.Num},u),i.allErrors||r.if((0,Wo.not)(u),()=>r.break())})}}Ba.validateAdditionalItems=n$;Ba.default=WH});var Fy=L(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.validateTuple=void 0;var o$=oe(),vl=me(),KH=cr(),GH={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return s$(t,"additionalItems",e);r.items=!0,!(0,vl.alwaysValidSchema)(r,e)&&t.ok((0,KH.validateArray)(t))}};function s$(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=vl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,o$._)`${s}.length`);r.forEach((d,m)=>{(0,vl.alwaysValidSchema)(a,d)||(n.if((0,o$._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:h}=a,p=r.length,f=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(m.strictTuples&&!f){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,vl.checkStrictMode)(a,g,m.strictTuples)}}}Za.validateTuple=s$;Za.default=GH});var i$=L(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});var JH=Fy(),XH={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,JH.validateTuple)(t,"items")};Hy.default=XH});var c$=L(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});var a$=oe(),YH=me(),QH=cr(),e2=zy(),t2={message:({params:{len:t}})=>(0,a$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,a$._)`{limit: ${t}}`},r2={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:t2,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,YH.alwaysValidSchema)(n,e)&&(o?(0,e2.validateAdditionalItems)(t,o):t.ok((0,QH.validateArray)(t)))}};Uy.default=r2});var u$=L(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var lr=oe(),Sl=me(),n2={message:({params:{min:t,max:e}})=>e===void 0?(0,lr.str)`must contain at least ${t} valid item(s)`:(0,lr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,lr._)`{minContains: ${t}}`:(0,lr._)`{minContains: ${t}, maxContains: ${e}}`},o2={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:n2,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,lr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Sl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Sl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Sl.alwaysValidSchema)(s,r)){let f=(0,lr._)`${l} >= ${i}`;a!==void 0&&(f=(0,lr._)`${f} && ${l} <= ${a}`),t.pass(f);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,lr._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>p(g)))}function h(f,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Sl.Type.Num,compositeRule:!0},f),g()})}function p(f){e.code((0,lr._)`${f}++`),a===void 0?e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,lr._)`${f} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0)))}}};By.default=o2});var p$=L(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.validateSchemaDeps=Ur.validatePropertyDeps=Ur.error=void 0;var Zy=oe(),s2=me(),qa=cr();Ur.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zy.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zy._)`{property: ${t},
460
+ missingProperty: ${n},
461
+ depsCount: ${e},
462
+ deps: ${r}}`};var i2={keyword:"dependencies",type:"object",schemaType:"object",error:Ur.error,code(t){let[e,r]=a2(t);l$(t,e),d$(t,r)}};function a2({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function l$(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,qa.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,qa.checkReportMissingProp)(t,u)}):(r.if((0,Zy._)`${c} && (${(0,qa.checkMissingProp)(t,a,s)})`),(0,qa.reportMissingProp)(t,s),r.else())}}Ur.validatePropertyDeps=l$;function d$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,s2.alwaysValidSchema)(s,e[a])||(r.if((0,qa.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ur.validateSchemaDeps=d$;Ur.default=i2});var f$=L(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var m$=oe(),c2=me(),u2={message:"property name must be valid",params:({params:t})=>(0,m$._)`{propertyName: ${t.propertyName}}`},l2={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:u2,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,c2.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,m$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};qy.default=l2});var Wy=L(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var kl=cr(),Sr=oe(),d2=cn(),wl=me(),p2={message:"must NOT have additional properties",params:({params:t})=>(0,Sr._)`{additionalProperty: ${t.additionalProperty}}`},m2={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:p2,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,wl.alwaysValidSchema)(i,r))return;let u=(0,kl.allSchemaProperties)(n.properties),l=(0,kl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Sr._)`${s} === ${d2.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let _=(0,wl.schemaRefOrVal)(i,n.properties,"properties");y=(0,kl.isOwnProperty)(e,_,g)}else u.length?y=(0,Sr.or)(...u.map(_=>(0,Sr._)`${g} === ${_}`)):y=Sr.nil;return l.length&&(y=(0,Sr.or)(y,...l.map(_=>(0,Sr._)`${(0,kl.usePattern)(t,_)}.test(${g})`))),(0,Sr.not)(y)}function h(g){e.code((0,Sr._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,wl.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,Sr.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,Sr.not)(y),()=>e.break()))}}function f(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:wl.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};Vy.default=m2});var y$=L(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var f2=Oa(),h$=cr(),Ky=me(),g$=Wy(),h2={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&g$.default.code(new f2.KeywordCxt(s,g$.default,"additionalProperties"));let i=(0,h$.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ky.mergeEvaluated.props(e,(0,Ky.toHash)(i),s.props));let a=i.filter(d=>!(0,Ky.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,h$.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Gy.default=h2});var v$=L(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var _$=cr(),El=oe(),b$=me(),x$=me(),g2={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,_$.allSchemaProperties)(r),c=a.filter(f=>(0,b$.alwaysValidSchema)(s,r[f]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof El.Name)&&(s.props=(0,x$.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let f of a)u&&h(f),s.allErrors?p(f):(e.var(l,!0),p(f),e.if(l))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,b$.checkStrictMode)(s,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function p(f){e.forIn("key",n,g=>{e.if((0,El._)`${(0,_$.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:x$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,El._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,El.not)(l),()=>e.break())})})}}};Jy.default=g2});var S$=L(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var y2=me(),_2={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,y2.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Xy.default=_2});var k$=L(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var b2=cr(),x2={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:b2.validateUnion,error:{message:"must match a schema in anyOf"}};Yy.default=x2});var w$=L(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var $l=oe(),v2=me(),S2={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,$l._)`{passingSchemas: ${t.passing}}`},k2={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:S2,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let m;(0,v2.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,$l._)`${c} && ${i}`).assign(i,!1).assign(a,(0,$l._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,$l.Name)})})}}};Qy.default=k2});var E$=L(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var w2=me(),E2={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,w2.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};e_.default=E2});var P$=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var Tl=oe(),T$=me(),$2={message:({params:t})=>(0,Tl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Tl._)`{failingKeyword: ${t.ifClause}}`},T2={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$2,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,T$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=$$(n,"then"),s=$$(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Tl.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let m=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(m,i),d?e.assign(d,(0,Tl._)`${l}`):t.setParams({ifClause:l})}}}};function $$(t,e){let r=t.schema[e];return r!==void 0&&!(0,T$.alwaysValidSchema)(t,r)}t_.default=T2});var R$=L(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var P2=me(),R2={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,P2.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};r_.default=R2});var C$=L(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var C2=zy(),O2=i$(),I2=Fy(),A2=c$(),N2=u$(),D2=p$(),M2=f$(),j2=Wy(),L2=y$(),z2=v$(),F2=S$(),H2=k$(),U2=w$(),B2=E$(),Z2=P$(),q2=R$();function V2(t=!1){let e=[F2.default,H2.default,U2.default,B2.default,Z2.default,q2.default,M2.default,j2.default,D2.default,L2.default,z2.default];return t?e.push(O2.default,A2.default):e.push(C2.default,I2.default),e.push(N2.default),e}n_.default=V2});var O$=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var Ke=oe(),W2={message:({schemaCode:t})=>(0,Ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ke._)`{format: ${t}}`},K2={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:W2,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?m():h();function m(){let p=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),f=r.const("fDef",(0,Ke._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ke._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Ke._)`${f}.type || "string"`).assign(y,(0,Ke._)`${f}.validate`),()=>r.assign(g,(0,Ke._)`"string"`).assign(y,f)),t.fail$data((0,Ke.or)(_(),b()));function _(){return c.strictSchema===!1?Ke.nil:(0,Ke._)`${i} && !${y}`}function b(){let v=l.$async?(0,Ke._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ke._)`${y}(${n})`,E=(0,Ke._)`(typeof ${y} == "function" ? ${v} : ${y}.test(${n}))`;return(0,Ke._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function h(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[f,g,y]=b(p);f===e&&t.pass(v());function _(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(E){let C=E instanceof RegExp?(0,Ke.regexpCode)(E):c.code.formats?(0,Ke._)`${c.code.formats}${(0,Ke.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:E,code:C});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Ke._)`${x}.validate`]:["string",E,x]}function v(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ke._)`await ${y}(${n})`}return typeof g=="function"?(0,Ke._)`${y}(${n})`:(0,Ke._)`${y}.test(${n})`}}}};o_.default=K2});var I$=L(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var G2=O$(),J2=[G2.default];s_.default=J2});var A$=L(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.contentVocabulary=ri.metadataVocabulary=void 0;ri.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ri.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var D$=L(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var X2=UE(),Y2=r$(),Q2=C$(),eU=I$(),N$=A$(),tU=[X2.default,Y2.default,(0,Q2.default)(),eU.default,N$.metadataVocabulary,N$.contentVocabulary];i_.default=tU});var j$=L(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.DiscrError=void 0;var M$;(function(t){t.Tag="tag",t.Mapping="mapping"})(M$||(Pl.DiscrError=M$={}))});var z$=L(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var ni=oe(),a_=j$(),L$=ll(),rU=Ia(),nU=me(),oU={message:({params:{discrError:t,tagName:e}})=>t===a_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ni._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},sU={keyword:"discriminator",type:"object",schemaType:"object",error:oU,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,ni._)`${r}${(0,ni.getProperty)(a)}`);e.if((0,ni._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:a_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let h=m();e.if(!1);for(let p in h)e.elseIf((0,ni._)`${u} === ${p}`),e.assign(c,d(h[p]));e.else(),t.error(!1,{discrError:a_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(h){let p=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(f,ni.Name),p}function m(){var h;let p={},f=y(o),g=!0;for(let v=0;v<i.length;v++){let E=i[v];if(E?.$ref&&!(0,nU.schemaHasRulesButRef)(E,s.self.RULES)){let x=E.$ref;if(E=L$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),E instanceof L$.SchemaEnv&&(E=E.schema),E===void 0)throw new rU.default(s.opts.uriResolver,s.baseId,x)}let C=(h=E?.properties)===null||h===void 0?void 0:h[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(E)),_(C,v)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:v}){return Array.isArray(v)&&v.includes(a)}function _(v,E){if(v.const)b(v.const,E);else if(v.enum)for(let C of v.enum)b(C,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(v,E){if(typeof v!="string"||v in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[v]=E}}}};c_.default=sU});var F$=L((HJ,iU)=>{iU.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var l_=L((Ne,u_)=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.MissingRefError=Ne.ValidationError=Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=Ne.Ajv=void 0;var aU=ME(),cU=D$(),uU=z$(),H$=F$(),lU=["/properties"],Rl="http://json-schema.org/draft-07/schema",oi=class extends aU.default{_addVocabularies(){super._addVocabularies(),cU.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(uU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(H$,lU):H$;this.addMetaSchema(e,Rl,!1),this.refs["http://json-schema.org/schema"]=Rl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Rl)?Rl:void 0)}};Ne.Ajv=oi;u_.exports=Ne=oi;u_.exports.Ajv=oi;Object.defineProperty(Ne,"__esModule",{value:!0});Ne.default=oi;var dU=Oa();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return dU.KeywordCxt}});var si=oe();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return si._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return si.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return si.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return si.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return si.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return si.CodeGen}});var pU=cl();Object.defineProperty(Ne,"ValidationError",{enumerable:!0,get:function(){return pU.default}});var mU=Ia();Object.defineProperty(Ne,"MissingRefError",{enumerable:!0,get:function(){return mU.default}})});var G$=L(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.formatNames=Zr.fastFormats=Zr.fullFormats=void 0;function Br(t,e){return{validate:t,compare:e}}Zr.fullFormats={date:Br(q$,f_),time:Br(p_(!0),h_),"date-time":Br(U$(!0),W$),"iso-time":Br(p_(),V$),"iso-date-time":Br(U$(),K$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:bU,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((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})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((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})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((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}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((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}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((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}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((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}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((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}))|:)))$/i,regex:$U,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:xU,int32:{type:"number",validate:kU},int64:{type:"number",validate:wU},float:{type:"number",validate:Z$},double:{type:"number",validate:Z$},password:!0,binary:!0};Zr.fastFormats={...Zr.fullFormats,date:Br(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,f_),time:Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h_),"date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,W$),"iso-time":Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,V$),"iso-date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,K$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Zr.formatNames=Object.keys(Zr.fullFormats);function fU(t){return t%4===0&&(t%100!==0||t%400===0)}var hU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,gU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function q$(t){let e=hU.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&fU(r)?29:gU[n])}function f_(t,e){if(t&&e)return t>e?1:t<e?-1:0}var d_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function p_(t){return function(r){let n=d_.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function h_(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function V$(t,e){if(!(t&&e))return;let r=d_.exec(t),n=d_.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var m_=/t|\s/i;function U$(t){let e=p_(t);return function(n){let o=n.split(m_);return o.length===2&&q$(o[0])&&e(o[1])}}function W$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function K$(t,e){if(!(t&&e))return;let[r,n]=t.split(m_),[o,s]=e.split(m_),i=f_(r,o);if(i!==void 0)return i||h_(n,s)}var yU=/\/|:/,_U=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function bU(t){return yU.test(t)&&_U.test(t)}var B$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function xU(t){return B$.lastIndex=0,B$.test(t)}var vU=-(2**31),SU=2**31-1;function kU(t){return Number.isInteger(t)&&t<=SU&&t>=vU}function wU(t){return Number.isInteger(t)}function Z$(){return!0}var EU=/[^\\]\\Z/;function $U(t){if(EU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var J$=L(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.formatLimitDefinition=void 0;var TU=l_(),kr=oe(),qn=kr.operators,Cl={formatMaximum:{okStr:"<=",ok:qn.LTE,fail:qn.GT},formatMinimum:{okStr:">=",ok:qn.GTE,fail:qn.LT},formatExclusiveMaximum:{okStr:"<",ok:qn.LT,fail:qn.GTE},formatExclusiveMinimum:{okStr:">",ok:qn.GT,fail:qn.LTE}},PU={message:({keyword:t,schemaCode:e})=>(0,kr.str)`should be ${Cl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kr._)`{comparison: ${Cl[t].okStr}, limit: ${e}}`};ii.formatLimitDefinition={keyword:Object.keys(Cl),type:"string",schemaType:"string",$data:!0,error:PU,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new TU.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,kr._)`${m}[${c.schemaCode}]`);t.fail$data((0,kr.or)((0,kr._)`typeof ${h} != "object"`,(0,kr._)`${h} instanceof RegExp`,(0,kr._)`typeof ${h}.compare != "function"`,d(h)))}function l(){let m=c.schema,h=a.formats[m];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:h,code:i.code.formats?(0,kr._)`${i.code.formats}${(0,kr.getProperty)(m)}`:void 0});t.fail$data(d(p))}function d(m){return(0,kr._)`${m}.compare(${r}, ${n}) ${Cl[o].fail} 0`}},dependencies:["format"]};var RU=t=>(t.addKeyword(ii.formatLimitDefinition),t);ii.default=RU});var eT=L((Va,Q$)=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var ai=G$(),CU=J$(),g_=oe(),X$=new g_.Name("fullFormats"),OU=new g_.Name("fastFormats"),y_=(t,e={keywords:!0})=>{if(Array.isArray(e))return Y$(t,e,ai.fullFormats,X$),t;let[r,n]=e.mode==="fast"?[ai.fastFormats,OU]:[ai.fullFormats,X$],o=e.formats||ai.formatNames;return Y$(t,o,r,n),e.keywords&&(0,CU.default)(t),t};y_.get=(t,e="full")=>{let n=(e==="fast"?ai.fastFormats:ai.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Y$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,g_._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Q$.exports=Va=y_;Object.defineProperty(Va,"__esModule",{value:!0});Va.default=y_});function IU(){let t=new tT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,rT.default)(t),t}var tT,rT,Ol,nT=S(()=>{tT=bi(l_(),1),rT=bi(eT(),1);Ol=class{constructor(e){this._ajv=e??IU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Il,oT=S(()=>{jo();Il=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),d=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==d.size||![...l].every(m=>d.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},ga,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Zs,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function sT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function iT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var aT=S(()=>{});var Al,cT=S(()=>{hw();jo();nT();oa();oT();aT();Al=class extends Gu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ha.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ol,this.setRequestHandler(Ih,n=>this._oninitialize(n)),this.setNotificationHandler(Ah,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Fh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ha.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Il(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=fw(this._capabilities,e)}setRequestHandler(e,r){let o=Nn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(nr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=An(Bs,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new B(G.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let p=An(js,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new B(G.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let h=An(ju,m);if(!h.success){let p=h.error instanceof Error?h.error.message:String(h.error);throw new B(G.InvalidParams,`Invalid tools/call result: ${p}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){iT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&sT(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:f0.includes(r)?r:Th,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Eu)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Hh,r):this.request({method:"sampling/createMessage",params:e},ga,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Zs,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Zs,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new B(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof B?i:new B(G.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Uh,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function __(t){return!!t&&typeof t=="object"&&lT in t}function dT(t){return t[lT]?.complete}var lT,uT,pT=S(()=>{lT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(uT||(uT={}))});var mT=S(()=>{});function NU(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!AU.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function DU(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function b_(t){let e=NU(t);return DU(t,e.warnings),e.isValid}var AU,fT=S(()=>{AU=/^[A-Za-z0-9._-]{1,128}$/});var Nl,hT=S(()=>{Nl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Dl=S(()=>{Gc();Gc()});function _T(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function bT(t){return"_def"in t||"_zod"in t||_T(t)}function x_(t){return typeof t!="object"||t===null||bT(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(_T)}function gT(t){if(t){if(x_(t))return Mo(t);if(!bT(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function jU(t){let e=Nn(t);return e?Object.entries(e).map(([r,n])=>{let o=zk(n),s=Fk(n);return{name:r,description:o,required:!s}}):[]}function Vn(t){let r=Nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function yT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ml,MU,Wa,xT=S(()=>{cT();oa();Eg();jo();pT();mT();fT();hT();Dl();Ml=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Al(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Nl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(Us)),this.server.assertCanSetRequestHandler(Vn(Bs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Ds(r.inputSchema);return o?Sg(o,{strictUnions:!0,pipeStrategy:"input"}):MU})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Ds(r.outputSchema);o&&(n.outputSchema=Sg(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Bs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new B(G.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new B(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof B&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Ds(e.inputSchema)??e.inputSchema,i=await yu(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=_u(a);throw new B(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Ds(e.outputSchema),s=await yu(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=_u(i);throw new B(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,l));let d=await n.taskStore.getTask(c);if(!d)throw new B(G.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vn(Lu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Lu,async e=>{switch(e.params.ref.type){case"ref/prompt":return C0(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return O0(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Wa;let s=Nn(n.argsSchema)?.[e.params.argument.name];if(!__(s))return Wa;let i=dT(s);if(!i)return Wa;let a=await i(e.params.argument.value,e.params.context);return yT(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Wa;throw new B(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Wa;let s=await o(e.params.argument.value,e.params.context);return yT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(zs)),this.server.assertCanSetRequestHandler(Vn(Fs)),this.server.assertCanSetRequestHandler(Vn(Du)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Fs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Du,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(G.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new B(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(Hs)),this.server.assertCanSetRequestHandler(Vn(Mu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Hs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?jU(r.argsSchema):void 0}))})),this.server.setRequestHandler(Mu,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Ds(n.argsSchema),s=await yu(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=_u(c);throw new B(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Mo(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Mo(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Ot?c._def?.innerType:c;return __(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){b_(e);let l={title:r,description:n,inputSchema:gT(o),outputSchema:gT(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&b_(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Mo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Mo(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(x_(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!x_(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},MU={type:"object",properties:{}};Wa={completion:{values:[],hasMore:!1}}});function LU(t){return S0.parse(JSON.parse(t))}function vT(t){return JSON.stringify(t)+`
463
+ `}var jl,ST=S(()=>{jo();jl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
464
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),LU(r)}clear(){this._buffer=void 0}}});import kT from"node:process";var Ll,wT=S(()=>{ST();Ll=class{constructor(e=kT.stdin,r=kT.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new jl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=vT(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var NT={};we(NT,{PolyglotExecutor:()=>ci,buildScriptFilename:()=>OT,buildShellScriptContent:()=>AT,buildSpawnOptions:()=>IT});import{spawn as ET,execSync as zU,execFileSync as RT}from"node:child_process";import{mkdtempSync as FU,writeFileSync as $T,rmSync as TT,existsSync as PT}from"node:fs";import{join as zl,resolve as CT}from"node:path";import{tmpdir as HU}from"node:os";function OT(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";if(n.includes("powershell")||n.includes("pwsh"))return"script.ps1";let o=n.split(/[\\/]/).pop()??n;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${UU[t]}`}function IT(t){return{windowsHide:t==="win32"}}function BU(t){return`'${t.replace(/'/g,"'\\''")}'`}function AT(t,e,r){return r==="win32"||!e?t:`export PATH=${BU(e)}
465
+ ${t}`}function v_(t){if(dr&&t.pid)try{zU(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var dr,UU,ZU,ci,S_=S(()=>{"use strict";Xo();dr=process.platform==="win32",UU={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};ZU=(()=>{if(dr)return process.env.TEMP??process.env.TMP??HU();try{let t=RT(process.platform==="darwin"?"getconf":"mktemp",process.platform==="darwin"?["DARWIN_USER_TEMP_DIR"]:["-u","-d"],{env:{...process.env,TMPDIR:void 0},encoding:"utf-8"}).trim(),e=process.platform==="darwin"?t:CT(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();ci=class{#e;#t;#n;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Yn()}get#o(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(dr?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:o,background:s=!1,cwd:i}=e,a=FU(zl(ZU,".ctx-mode-"));try{let c=this.#a(a,n,r),u=jd(this.#n,r,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=r==="shell"?i??this.#o:a,d=await this.#i(u,l,a,o,s);if(!d.backgrounded)try{TT(a,{recursive:!0,force:!0})}catch{}return d}catch(c){try{TT(a,{recursive:!0,force:!0})}catch{}throw c}}async executeFile(e){let{path:r,language:n,code:o,timeout:s}=e,i=CT(this.#o,r),a=this.#l(i,n,o);return this.execute({language:n,code:a,timeout:s})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
466
+
467
+ import "fmt"
468
+
469
+ func main() {
470
+ ${r}
471
+ }
472
+ `),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
473
+ ${r}`),n==="elixir"&&PT(zl(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(zl(this.#o,"_build/dev/lib"))}, "*/ebin"))
474
+ |> Enum.each(&Code.prepend_path/1)
475
+
476
+ ${r}`);let o=zl(e,OT(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?$T(o,AT(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):$T(o,r,"utf-8"),o}async#c(e,r,n){let o=dr?".exe":"",s=e.replace(/\.rs$/,"")+o;try{RT("rustc",[e,"-o",s],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
477
+ ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=dr&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;dr&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=dr?e.slice(1).map(b=>b.replace(/\\/g,"/")):e.slice(1);let l={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!dr,...IT(process.platform)},d;if(a){let b=[c,...u].map(v=>/\s/.test(v)?JSON.stringify(v):v).join(" ");d=ET(b,[],{...l,shell:!0})}else d=ET(c,u,{...l,shell:!1});let m=!1,h=!1,p=o===void 0?void 0:setTimeout(()=>{if(m=!0,s){h=!0,d.pid&&this.#s.add(d.pid),d.unref(),d.stdout.destroy(),d.stderr.destroy();let b=Buffer.concat(f).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");i({stdout:b,stderr:v,exitCode:0,timedOut:!0,backgrounded:!0})}else v_(d)},o),f=[],g=[],y=0,_=!1;d.stdout.on("data",b=>{y+=b.length,y<=this.#e?f.push(b):_||(_=!0,v_(d))}),d.stderr.on("data",b=>{y+=b.length,y<=this.#e?g.push(b):_||(_=!0,v_(d))}),d.on("close",b=>{if(clearTimeout(p),h)return;let v=Buffer.concat(f).toString("utf-8"),E=Buffer.concat(g).toString("utf-8");_&&(E+=`
478
+ [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:v,stderr:E,exitCode:m?1:b??1,timedOut:m})}),d.on("error",b=>{clearTimeout(p),!h&&i({stdout:"",stderr:b.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!n.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=r,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",dr&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=dr?"":"/usr/local/bin:/usr/bin:/bin"),dr){o.MSYS_NO_PATHCONV="1",o.MSYS2_ARG_CONV_EXCL="*";let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=dr?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(PT(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,r,n){let o=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
479
+ const file_path = FILE_CONTENT_PATH;
480
+ const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
481
+ ${n}`;case"python":return`FILE_CONTENT_PATH = ${o}
482
+ file_path = FILE_CONTENT_PATH
483
+ with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
484
+ FILE_CONTENT = _f.read()
485
+ ${n}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
486
+ file_path=${s}
487
+ FILE_CONTENT=$(cat ${s})
488
+ ${n}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
489
+ file_path = FILE_CONTENT_PATH
490
+ FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
491
+ ${n}`;case"go":return`package main
492
+
493
+ import (
494
+ "fmt"
495
+ "os"
496
+ )
497
+
498
+ var FILE_CONTENT_PATH = ${o}
499
+ var file_path = FILE_CONTENT_PATH
512
500
 
513
- `).trim();if(y.length===0)return;let v=f.length>1?`${l} (${h})`:l;h++,n.push({title:v,content:y,hasCode:y.includes("```")}),p=[]};for(let y of f){p.push(y);let v=p.join(`
501
+ func main() {
502
+ b, _ := os.ReadFile(FILE_CONTENT_PATH)
503
+ FILE_CONTENT := string(b)
504
+ _ = FILE_CONTENT
505
+ _ = fmt.Sprint()
506
+ ${n}
507
+ }
508
+ `;case"rust":return`#![allow(unused_variables)]
509
+ use std::fs;
514
510
 
515
- `);Buffer.byteLength(v)>r&&p.length>1&&(p.pop(),g(),p=[y])}g(),i=[]},u=0;for(;u<o.length;){let d=o[u];if(/^[-_*]{3,}\s*$/.test(d)){c(),u++;continue}let l=d.match(/^(#{1,4})\s+(.+)$/);if(l){c();let f=l[1].length,p=l[2].trim();for(;s.length>0&&s[s.length-1].level>=f;)s.pop();s.push({level:f,text:p}),a=p,i.push(d),u++;continue}let m=d.match(/^(`{3,})(.*)?$/);if(m){let f=m[1],p=[d];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(f)&&o[u].trim()===f){u++;break}u++}i.push(...p);continue}i.push(d),u++}return c(),n}#W(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let d=c.trim();return{title:d.split(`
516
- `)[0].slice(0,80)||`Section ${u+1}`,content:d}}).filter(c=>c.content.length>0);let o=e.split(`
517
- `);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let d=c+1,l=Math.min(c+u.length,o.length),m=u[0]?.trim().slice(0,80);s.push({title:m||`Lines ${d}-${l}`,content:u.join(`
518
- `)})}return s}#U(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#K(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#J(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=d=>{if(a.length===0)return;let l=this.#K(s,c,d,a,i);n.push({title:l,content:JSON.stringify(a,null,2),hasCode:!0})};for(let d=0;d<e.length;d++){a.push(e[d]);let l=JSON.stringify(a,null,2);Buffer.byteLength(l)>o&&a.length>1&&(a.pop(),u(d-1),a=[e[d]],c=d)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function Jy(t,e){return t===void 0?e:`${t}::${e}`}var B$=S(()=>{"use strict"});import{readFileSync as V$,realpathSync as hU}from"node:fs";import{resolve as Ra}from"node:path";function W$(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function gU(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function yU(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function q$(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function _U(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=yU(o),a=q$(s);r=`^${i}(\\s${a})?$`}else r=`^${q$(t)}$`;return new RegExp(r,e?"i":"")}function vU(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function bU(t,e,r=!1){for(let n of e){let o=W$(n);if(o&&_U(o,r).test(t))return n}return null}function xU(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function Yy(t){let e;try{e=V$(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&W$(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function Xy(t,e){let r=[];if(t){let o=Ra(t,".claude","settings.local.json"),s=Yy(o);s&&r.push(s);let i=Ra(t,".claude","settings.json"),a=Yy(i);a&&r.push(a)}let n=e!==void 0?[e]:_p();for(let o of n){let s=Yy(o);s&&r.push(s)}return r}function Sl(t,e,r){let n=[],o=i=>{let a;try{a=V$(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let d=[];for(let l of u){if(typeof l!="string")continue;let m=gU(l);m&&m.tool===t&&d.push(m.glob)}return d};if(e){let i=o(Ra(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=o(Ra(e,".claude","settings.json"));a!==null&&n.push(a)}let s=r!==void 0?[r]:_p();for(let i of s){let a=o(i);a!==null&&n.push(a)}return n}function Qy(t,e,r=process.platform==="win32"){let n=xU(t);for(let o of n)for(let s of e){let i=bU(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function kl(t,e,r=process.platform==="win32",n){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),n){let i=Ra(n,t);s.add(o(i));try{s.add(o(hU(i)))}catch{}}for(let i of e)for(let a of i){let c=vU(o(a),r);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function kU(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function G$(t,e){let r=SU[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...kU(t)),n}var SU,K$=S(()=>{"use strict";hn();SU={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});function e_(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
511
+ fn main() {
512
+ let file_content_path = ${o};
513
+ let file_path = file_content_path;
514
+ let file_content = fs::read_to_string(file_content_path).unwrap();
515
+ ${n}
516
+ }
517
+ `;case"php":return`<?php
518
+ $FILE_CONTENT_PATH = ${o};
519
+ $file_path = $FILE_CONTENT_PATH;
520
+ $FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
521
+ ${n}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
522
+ my $file_path = $FILE_CONTENT_PATH;
523
+ open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
524
+ my $FILE_CONTENT = do { local $/; <$fh> };
525
+ close($fh);
526
+ ${n}`;case"r":return`FILE_CONTENT_PATH <- ${o}
527
+ file_path <- FILE_CONTENT_PATH
528
+ FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
529
+ FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
530
+ ${n}`;case"elixir":return`file_content_path = ${o}
531
+ file_path = file_content_path
532
+ file_content = File.read!(file_content_path)
533
+ ${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
534
+ var file_path = FILE_CONTENT_PATH;
535
+ var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
536
+ ${n}`}}}});import{cpus as qU}from"node:os";async function k_(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,r),i=n?Math.max(1,qU().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let h=l++;if(h>=t.length)return;try{let p=await t[h].run();u[h]={status:"fulfilled",value:p}}catch(p){u[h]={status:"rejected",reason:p}}o?.(h,u[h])}}let m=[];for(let h=0;h<a;h++)m.push(d());return await Promise.allSettled(m),{settled:u,effectiveConcurrency:a,capped:c}}var DT=S(()=>{"use strict"});function w_(t,e){return t===void 0?e:`${t}::${e}`}var MT=S(()=>{"use strict"});function E_(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
519
537
 
520
538
  stdout:
521
539
  ${n}
522
540
 
523
541
  stderr:
524
- ${o}`}}var J$=S(()=>{"use strict"});import{execFileSync as wU}from"node:child_process";function EU(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=wU("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function $U(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??EU,n=e(),o=r();return()=>{let s=e();return!(s!==n||s===0||s===1||!Number.isNaN(o)&&o>1&&r()===1)}}function PU(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function Y$(t){let e=t.checkIntervalMs??PU(),r=t.isParentAlive??TU,n=!1,o=()=>{n||(n=!0,t.onShutdown())},s=setInterval(()=>{r()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{r()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}var TU,X$=S(()=>{"use strict";TU=$U()});function Q$(t,e){if(e<=0)return"";if(t.length<=e)return t;let r=e,n=t.charCodeAt(r-1);return n>=55296&&n<=56319&&(r-=1),t.slice(0,r)}var eT=S(()=>{"use strict"});import{existsSync as t_,unlinkSync as RU}from"node:fs";import{join as Ca}from"node:path";function r_(t,e){try{return RU(t),e.push(t),!0}catch{return!1}}function wl(t,e){let r=!1;for(let n of CU)r_(`${t}${n}`,e)&&n===""&&(r=!0);return r}function tT(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],d=[],l=c??(a?"session":"project");if(l==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(l==="session"&&a){let _=uc(e),b=gt(e),x=Ur(e),P=b===x?[b]:[b,x],E=!1;for(let L of P){let w=Ca(r,`${L}${_}.db`);if(!t_(w))continue;let F=null;try{F=new ur({dbPath:w});let U=F.getEvents(a).length;F.deleteSession(a),U>0&&(E=!0)}catch{}finally{try{F?.close()}catch{}}}E&&u.push(`session rows for ${a}`);let R=[];if(n&&t_(n)&&R.push(n),o){let L=gt(e),w=Ur(e),F=L===w?[L]:[L,w];for(let U of F){let te=Ca(o,`${U}.db`);t_(te)&&!R.includes(te)&&R.push(te)}}let A=!1;for(let L of R)try{let w=Qe(),F=new w(L,{timeout:3e4});try{let U=F.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;F.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),F.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),U>0&&(A=!0)}finally{try{F.close()}catch{}}}catch{}return A&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:d}}let m=!1;if(n&&wl(n,d)&&(m=!0),o){let _=gt(e),b=Ur(e),x=_===b?[_]:[_,b];for(let P of x){let E=Ca(o,`${P}.db`);wl(E,d)&&(m=!0)}}if(m&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=Ca(s,`${i}.db`);wl(_,d)}let f=uc(e),p=gt(e),h=Ur(e),g=p===h?[p]:[p,h],y=!1,v=!1;for(let _ of g){let b=Ca(r,`${_}${f}`);wl(`${b}.db`,d)&&(y=!0),r_(`${b}-events.md`,d)&&(v=!0),r_(`${b}.cleanup`,d)}return y&&u.push("session events DB"),v&&u.push("session events markdown"),{deleted:u,wipedPaths:d}}var CU,rT=S(()=>{"use strict";ln();Tr();CU=["","-wal","-shm"]});import{existsSync as OU}from"node:fs";function n_(t,e){try{if(!OU(t))return;let r=new ur({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function nT(t){n_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function oT(t){n_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function sT(t){n_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var iT=S(()=>{"use strict";Tr()});import{existsSync as aT}from"node:fs";function cT(t,e,r){try{if(!aT(t))return;let n=new ur({dbPath:t});try{let o=n.getLatestSessionId();if(!o)return;n.incrementToolCall(o,e,r)}finally{n.close()}}catch{}}function uT(t){try{if(!aT(t))return null;let e=new ur({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),o={},s={};for(let[a,c]of Object.entries(n.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}var lT=S(()=>{"use strict";Tr()});import{existsSync as o_,readFileSync as IU,readdirSync as AU,statSync as NU}from"node:fs";import{join as Bs,isAbsolute as DU}from"node:path";function mT(t,e=5,r,n,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?pT(r,a):null)??n??qe(),d=o?.getMemoryDir(r),l=Bs(u,"memory"),m=r?Bs(l,gt(r)):l,f=d?pT(r,d):m,p=[];if(r)for(let h of i){let g=Bs(r,h);o_(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==r)for(let h of i){let g=Bs(u,h);o_(g)&&p.push({path:g,label:`user/${h}`})}if(f&&o_(f))try{let h=AU(f).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:Bs(f,g),label:`memory/${g}`})}catch(h){dT&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
525
- `)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=NU(h.path),g.size>1e6)continue}catch{continue}let y=IU(h.path,"utf-8"),v=y.toLowerCase();for(let _ of t){if(s.length>=e)break;let x=_.toLowerCase().split(/\s+/).filter(E=>E.length>=3);if(x.some(E=>{try{return new RegExp(`\\b${E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return v.includes(E)}})){let E=x.reduce((U,te)=>{let Ze=v.indexOf(te);return Ze>=0&&(U<0||Ze<U)?Ze:U},-1),R=Math.max(0,E-200),A=Math.min(y.length,E+500),L=y.lastIndexOf(`
526
-
527
- `,R),w=y.indexOf(`
528
-
529
- `,A);L>=0&&(R=L+2),w>=0&&(A=w);let F=y.slice(R,A).trim();s.push({title:`[auto-memory] ${h.label}`,content:F,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){dT&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
530
- `)}}return s.slice(0,e)}function pT(t,e){return e?DU(e)||!t?e:Bs(t,e):t??""}var dT,fT=S(()=>{"use strict";hn();Tr();dT=process.env.DEBUG?.includes("context-mode")});function hT(t){let{query:e,limit:r,store:n,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:d}=t,l=[],m=new Date().toISOString();try{let f=n.searchWithFallback(e,r,s,i);l.push(...f.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||m,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(f){s_&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
531
- `)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",s);l.push(...f.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(f){s_&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
532
- `)}try{let f=mT([e],r,c,u,d);l.push(...f)}catch(f){s_&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
533
- `)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&l.sort((f,p)=>(f.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var s_,gT=S(()=>{"use strict";fT();s_=process.env.DEBUG?.includes("context-mode")});import*as Ge from"node:fs";import*as yT from"node:os";import*as qs from"node:path";function El(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function zU(t){if(!Ge.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Ge.readdirSync(t.projectsRoot)){let o=qs.join(t.projectsRoot,n),s;try{s=Ge.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Ge.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=qs.join(o,a);try{let u=Ge.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=Ge.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Ge.readSync(n,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
534
- `).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{Ge.closeSync(n)}}catch{}}function LU(t){let e=t?.codexHome??process.env.CODEX_HOME??qs.join(yT.homedir(),".codex"),r=qs.join(e,"sessions");if(!Ge.existsSync(r))return null;let n,o=0;try{for(let s of Ge.readdirSync(r)){if(!s.endsWith(".jsonl"))continue;let i=qs.join(r,s);try{let a=Ge.statSync(i).mtimeMs;a>o&&(o=a,n=i)}catch{}}}catch{return null}if(!n||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-o>t.transcriptMaxAgeMs)return null;try{let s=Ge.openSync(n,"r");try{let i=Buffer.alloc(8192),a=Ge.readSync(s,i,0,i.length,0),u=i.subarray(0,a).toString("utf-8").split(`
535
- `,1)[0];if(!u||!u.trim())return null;try{let l=JSON.parse(u)?.meta?.cwd;return typeof l!="string"||l.length===0||El(l)?null:l}catch{return null}}finally{Ge.closeSync(s)}}catch{return null}}function _T(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...gp(a),...MU]:jU;for(let d of u){let l=e[d];if(l&&!El(l))return l}if(o){let d=zU({projectsRoot:o,maxAgeMs:s,nowMs:i});if(d&&!El(d))return d}if(a==="codex"){let d=LU({codexHome:c,transcriptMaxAgeMs:s,now:i});if(d)return d}return n&&!El(n)?n:r}var MU,jU,vT=S(()=>{"use strict";yn();MU=["CONTEXT_MODE_PROJECT_DIR"],jU=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"]});import{execFileSync as FU}from"node:child_process";import{existsSync as tn,readdirSync as Vs,statSync as UU}from"node:fs";import{homedir as Cl}from"node:os";import{join as Lt,sep as HU}from"node:path";function TT(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function BU(t){let e=t?.home??Cl();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,o])=>{let s=Lt(e,...o,"context-mode");return{name:n,sessionsDir:Lt(s,"sessions"),contentDir:Lt(s,"content")}})}function qU(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Oa(t){let e=qe(),r=t?.sessionsDir??Lt(e,"context-mode","sessions"),n=t?.memoryRoot??Lt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(tn(r)){let f=[];try{f=Vs(r).filter(p=>p.endsWith(".db"))}catch{}if(f.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Qe()}catch{}if(p)for(let h of f){let g=Lt(r,h);try{let y=new p(g,{readonly:!0});try{let v=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=v?.cnt??0,s+=_?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let x of b)x.category&&(u[x.category]=(u[x.category]??0)+(x.cnt??0))}catch{}try{let b=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();b?.bytes&&(i+=b.bytes)}catch{}try{let b=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(b?.t){let x=b.t.endsWith("Z")?b.t:b.t+"Z",P=Date.parse(x);Number.isFinite(P)&&P<a&&(a=P)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let x of b)x.p&&c.add(x.p)}catch{}}finally{y.close()}}catch{}}}}let d=0,l=0,m={};if(tn(n)){let f=[];try{f=Vs(n).filter(p=>{try{return UU(Lt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of f){let h=Lt(n,p,"memory");if(!tn(h))continue;let g=[];try{g=Vs(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let y of g){let v=qU(y);m[v]=(m[v]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:m,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function PT(t){let e=t.sessionsDir??Lt(Cl(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!tn(e))return n;let o=[];try{o=Vs(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(o.length===0)return n;let s=null;try{s=t.loadDatabase?t.loadDatabase():Qe()}catch{return n}if(!s)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,m=0,f=0,p=new Map,h=_=>Math.floor(_/864e5)*864e5;for(let _ of o){let b=Lt(e,_),x=!1;try{let P=new s(b,{readonly:!0});try{let E=P.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let A of E)A.category&&(i[A.category]=(i[A.category]??0)+(A.cnt??0),a+=A.cnt??0,x=!0);let R=P.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(R?.mn){let A=Date.parse(R.mn+(R.mn.endsWith("Z")?"":"Z"));Number.isFinite(A)&&A<l&&(l=A)}if(R?.mx){let A=Date.parse(R.mx+(R.mx.endsWith("Z")?"":"Z"));Number.isFinite(A)&&A>m&&(m=A)}try{let A=P.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let L of A){if(!L.sec)continue;let w=parseInt(L.sec,10)*1e3;if(!Number.isFinite(w))continue;let F=h(w),U=p.get(F)??{count:0,rescueBytes:0};U.count+=L.cnt??0,p.set(F,U)}}catch{}try{let A=P.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(A?.bytes&&(u+=A.bytes),A?.n&&(d+=A.n),A?.lastSec){let L=parseInt(A.lastSec,10)*1e3;if(Number.isFinite(L)&&L>f&&(f=L),Number.isFinite(L)&&(A?.bytes??0)>0){let w=h(L),F=p.get(w)??{count:0,rescueBytes:0};F.rescueBytes=Math.max(F.rescueBytes,A.bytes),p.set(w,F)}}}catch{}}finally{P.close()}}catch{}x&&c++}let g=l<m?(m-l)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,b])=>({category:_,count:b,label:Tl[_]||_})).sort((_,b)=>b.count-_.count),v=[...p.entries()].sort((_,b)=>_[0]-b[0]).map(([_,b])=>({ms:_,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:y,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:m>0?m:0,lastRescueMs:f>0?f:void 0,byDay:v}}function VU(t,e,r){if(!t||!e||!tn(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():Qe()}catch{return 0}if(!n)return 0;try{let o=new n(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
536
- FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function RT(t,e){if(!t||!tn(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():Qe()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let o=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
537
- FROM chunks`).get();return Number(o?.bytes??0)}finally{n.close()}}catch{return 0}}function Ia(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Lt(Cl(),".claude","context-mode","sessions");if(!tn(r))return e;let n=[];try{n=Vs(r).filter(l=>!(!l.endsWith(".db")||t.worktreeHash&&!l.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():Qe()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let l of n){let m=Lt(r,l);yv(m,o);try{let f=new o(m,{readonly:!0});try{if(t.sessionId){let p=f.prepare(`SELECT
542
+ ${o}`}}var jT=S(()=>{"use strict"});import{execFileSync as VU}from"node:child_process";function WU(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=VU("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function KU(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??WU,n=e(),o=r();return()=>{let s=e();return!(s!==n||s===0||s===1||!Number.isNaN(o)&&o>1&&r()===1)}}function JU(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function LT(t){let e=t.checkIntervalMs??JU(),r=t.isParentAlive??GU,n=!1,o=()=>{n||(n=!0,t.onShutdown())},s=setInterval(()=>{r()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{r()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}var GU,zT=S(()=>{"use strict";GU=KU()});function FT(t,e){if(e<=0)return"";if(t.length<=e)return t;let r=e,n=t.charCodeAt(r-1);return n>=55296&&n<=56319&&(r-=1),t.slice(0,r)}var HT=S(()=>{"use strict"});import{existsSync as $_,unlinkSync as XU}from"node:fs";import{join as Ka}from"node:path";function T_(t,e){try{return XU(t),e.push(t),!0}catch{return!1}}function Fl(t,e){let r=!1;for(let n of YU)T_(`${t}${n}`,e)&&n===""&&(r=!0);return r}function UT(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let b=Ci(e),v=nt(e),E=Ar(e),C=v===E?[v]:[v,E],x=!1;for(let N of C){let R=Ka(r,`${N}${b}.db`);if(!$_(R))continue;let O=null;try{O=new Gt({dbPath:R});let F=O.getEvents(a).length;O.deleteSession(a),F>0&&(x=!0)}catch{}finally{try{O?.close()}catch{}}}x&&u.push(`session rows for ${a}`);let k=[];if(n&&$_(n)&&k.push(n),o){let N=nt(e),R=Ar(e),O=N===R?[N]:[N,R];for(let F of O){let K=Ka(o,`${F}.db`);$_(K)&&!k.includes(K)&&k.push(K)}}let P=!1;for(let N of k)try{let R=rt(),O=new R(N,{timeout:3e4});try{let F=O.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;O.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),O.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),F>0&&(P=!0)}finally{try{O.close()}catch{}}}catch{}return P&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let m=!1;if(n&&Fl(n,l)&&(m=!0),o){let b=nt(e),v=Ar(e),E=b===v?[b]:[b,v];for(let C of E){let x=Ka(o,`${C}.db`);Fl(x,l)&&(m=!0)}}if(m&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let b=Ka(s,`${i}.db`);Fl(b,l)}let h=Ci(e),p=nt(e),f=Ar(e),g=p===f?[p]:[p,f],y=!1,_=!1;for(let b of g){let v=Ka(r,`${b}${h}`);Fl(`${v}.db`,l)&&(y=!0),T_(`${v}-events.md`,l)&&(_=!0),T_(`${v}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}var YU,BT=S(()=>{"use strict";bn();Jt();YU=["","-wal","-shm"]});import{existsSync as QU}from"node:fs";function P_(t,e){try{if(!QU(t))return;let r=new Gt({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function ZT(t){P_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function qT(t){P_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function VT(t){P_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var WT=S(()=>{"use strict";Jt()});import{existsSync as KT}from"node:fs";function GT(t,e,r){try{if(!KT(t))return;let n=new Gt({dbPath:t});try{let o=n.getLatestSessionId();if(!o)return;n.incrementToolCall(o,e,r)}finally{n.close()}}catch{}}function JT(t){try{if(!KT(t))return null;let e=new Gt({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),o={},s={};for(let[a,c]of Object.entries(n.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}var XT=S(()=>{"use strict";Jt()});import{existsSync as R_,readFileSync as eB,readdirSync as tB,statSync as rB}from"node:fs";import{join as ui,isAbsolute as nB}from"node:path";function eP(t,e=5,r,n,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?QT(r,a):null)??n??qe(),l=o?.getMemoryDir(r),d=ui(u,"memory"),m=r?ui(d,nt(r)):d,h=l?QT(r,l):m,p=[];if(r)for(let f of i){let g=ui(r,f);R_(g)&&p.push({path:g,label:`project/${f}`})}if(u&&u!==r)for(let f of i){let g=ui(u,f);R_(g)&&p.push({path:g,label:`user/${f}`})}if(h&&R_(h))try{let f=tB(h).filter(g=>g.endsWith(".md"));for(let g of f)p.push({path:ui(h,g),label:`memory/${g}`})}catch(f){YT&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
543
+ `)}for(let f of p){if(s.length>=e)break;try{let g;try{if(g=rB(f.path),g.size>1e6)continue}catch{continue}let y=eB(f.path,"utf-8"),_=y.toLowerCase();for(let b of t){if(s.length>=e)break;let E=b.toLowerCase().split(/\s+/).filter(x=>x.length>=3);if(E.some(x=>{try{return new RegExp(`\\b${x.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(x)}})){let x=E.reduce((F,K)=>{let ge=_.indexOf(K);return ge>=0&&(F<0||ge<F)?ge:F},-1),k=Math.max(0,x-200),P=Math.min(y.length,x+500),N=y.lastIndexOf(`
544
+
545
+ `,k),R=y.indexOf(`
546
+
547
+ `,P);N>=0&&(k=N+2),R>=0&&(P=R);let O=y.slice(k,P).trim();s.push({title:`[auto-memory] ${f.label}`,content:O,source:f.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){YT&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
548
+ `)}}return s.slice(0,e)}function QT(t,e){return e?nB(e)||!t?e:ui(t,e):t??""}var YT,tP=S(()=>{"use strict";kn();Jt();YT=process.env.DEBUG?.includes("context-mode")});function rP(t){let{query:e,limit:r,store:n,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,m=[],h=new Date().toISOString(),p;if(typeof d=="string"&&a)try{p=new Set(a.getSessionIdsForProject(d))}catch(f){Hl&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${f}
549
+ `)}try{let f=n.searchWithFallback(e,r,s,i,"like",p);m.push(...f.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||h,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(f){Hl&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
550
+ `)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",s);m.push(...f.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(f){Hl&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
551
+ `)}try{let f=eP([e],r,c,u,l);m.push(...f)}catch(f){Hl&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
552
+ `)}}for(let f of m)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&m.sort((f,g)=>(f.timestamp||"").localeCompare(g.timestamp||"")),m.slice(0,r)}var Hl,nP=S(()=>{"use strict";tP();Hl=process.env.DEBUG?.includes("context-mode")});function oB(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function oP(t){let e=t?{project:M.string().optional().describe("Project scope. Default (omit): this session's project \u2014 auto-resolved from the host adapter. 'global': span every project in the shared store (cross-project recall). <absolute-path>: scope to that specific project directory.")}:{};return M.object({queries:M.preprocess(oB,M.array(M.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:M.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:M.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:M.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:M.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory."),...e})}function sP(t,e,r){if(e)return t===void 0?r():t==="global"?null:t}var C_,iP=S(()=>{"use strict";Dl();C_=!!process.env.CONTEXT_MODE_PROJECT_DIR});import*as Je from"node:fs";import*as aP from"node:os";import*as li from"node:path";function Ul(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function aB(t){if(!Je.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Je.readdirSync(t.projectsRoot)){let o=li.join(t.projectsRoot,n),s;try{s=Je.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Je.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=li.join(o,a);try{let u=Je.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=Je.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Je.readSync(n,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
553
+ `).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{Je.closeSync(n)}}catch{}}function cB(t){let e=t?.codexHome??process.env.CODEX_HOME??li.join(aP.homedir(),".codex"),r=li.join(e,"sessions");if(!Je.existsSync(r))return null;let n=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Je.readdirSync(u)}catch{return}d.sort().reverse();for(let m of d){if(s>=o)return;s++;let h=li.join(u,m),p;try{p=Je.statSync(h)}catch{continue}if(p.isDirectory()){l<n&&c(h,l+1);continue}if(!p.isFile()||!m.endsWith(".jsonl"))continue;let f=p.mtimeMs;f>a&&(a=f,i=h)}};try{c(r,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Je.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Je.readSync(u,l,0,l.length,0),m=l.subarray(0,d).toString("utf-8");for(let h of m.split(`
554
+ `).slice(0,10))if(h.trim())try{let p=JSON.parse(h),f=p?.meta?.cwd??(p?.type==="session_meta"?p?.payload?.cwd:void 0);if(typeof f!="string"||f.length===0)continue;return Ul(f)?null:f}catch{return null}}finally{Je.closeSync(u)}}catch{return null}return null}function cP(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...Hp(a),...sB]:iB;for(let l of u){let d=e[l];if(d&&!Ul(d))return d}if(o){let l=aB({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Ul(l))return l}if(a==="codex"){let l=cB({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return n&&!Ul(n)?n:r}var sB,iB,uP=S(()=>{"use strict";$n();sB=["CONTEXT_MODE_PROJECT_DIR"],iB=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"]});import{execFileSync as uB}from"node:child_process";import{existsSync as dn,readdirSync as di,statSync as lB}from"node:fs";import{homedir as Wl}from"node:os";import{join as Bt,sep as dB}from"node:path";function _P(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function mB(t){let e=t?.home??Wl();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,o])=>{let s=Bt(e,...o,"context-mode");return{name:n,sessionsDir:Bt(s,"sessions"),contentDir:Bt(s,"content")}})}function fB(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Ga(t){let e=qe(),r=t?.sessionsDir??Bt(e,"context-mode","sessions"),n=t?.memoryRoot??Bt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(dn(r)){let h=[];try{h=di(r).filter(p=>p.endsWith(".db"))}catch{}if(h.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():rt()}catch{}if(p)for(let f of h){let g=Bt(r,f);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),b=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=b?.cnt??0;try{let v=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let E of v)E.category&&(u[E.category]=(u[E.category]??0)+(E.cnt??0))}catch{}try{let v=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();v?.bytes&&(i+=v.bytes)}catch{}try{let v=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(v?.t){let E=v.t.endsWith("Z")?v.t:v.t+"Z",C=Date.parse(E);Number.isFinite(C)&&C<a&&(a=C)}}catch{}try{let v=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let E of v)E.p&&c.add(E.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,m={};if(dn(n)){let h=[];try{h=di(n).filter(p=>{try{return lB(Bt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of h){let f=Bt(n,p,"memory");if(!dn(f))continue;let g=[];try{g=di(f).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=fB(y);m[_]=(m[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:m,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function bP(t){let e=t.sessionsDir??Bt(Wl(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!dn(e))return n;let o=[];try{o=di(e).filter(b=>!(!b.endsWith(".db")||t.worktreeHash&&!b.startsWith(t.worktreeHash)))}catch{return n}if(o.length===0)return n;let s=null;try{s=t.loadDatabase?t.loadDatabase():rt()}catch{return n}if(!s)return n;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,m=0,h=0,p=new Map,f=b=>Math.floor(b/864e5)*864e5;for(let b of o){let v=Bt(e,b),E=!1;try{let C=new s(v,{readonly:!0});try{let x=C.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let P of x)P.category&&(i[P.category]=(i[P.category]??0)+(P.cnt??0),a+=P.cnt??0,E=!0);let k=C.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(k?.mn){let P=Date.parse(k.mn+(k.mn.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P<d&&(d=P)}if(k?.mx){let P=Date.parse(k.mx+(k.mx.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P>m&&(m=P)}try{let P=C.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let N of P){if(!N.sec)continue;let R=parseInt(N.sec,10)*1e3;if(!Number.isFinite(R))continue;let O=f(R),F=p.get(O)??{count:0,rescueBytes:0};F.count+=N.cnt??0,p.set(O,F)}}catch{}try{let P=C.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(P?.bytes&&(u+=P.bytes),P?.n&&(l+=P.n),P?.lastSec){let N=parseInt(P.lastSec,10)*1e3;if(Number.isFinite(N)&&N>h&&(h=N),Number.isFinite(N)&&(P?.bytes??0)>0){let R=f(N),O=p.get(R)??{count:0,rescueBytes:0};O.rescueBytes=Math.max(O.rescueBytes,P.bytes),p.set(R,O)}}}catch{}}finally{C.close()}}catch{}E&&c++}let g=d<m?(m-d)/864e5:0,y=Object.entries(i).filter(([,b])=>b>0).map(([b,v])=>({category:b,count:v,label:Zl[b]||b})).sort((b,v)=>v.count-b.count),_=[...p.entries()].sort((b,v)=>b[0]-v[0]).map(([b,v])=>({ms:b,count:v.count,...v.rescueBytes>0?{rescueBytes:v.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:m>0?m:0,lastRescueMs:h>0?h:void 0,byDay:_}}function hB(t,e,r){if(!t||!e||!dn(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():rt()}catch{return 0}if(!n)return 0;try{let o=new n(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
555
+ FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function xP(t,e){if(!t||!dn(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():rt()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let o=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
556
+ FROM chunks`).get();return Number(o?.bytes??0)}finally{n.close()}}catch{return 0}}function Ja(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Bt(Wl(),".claude","context-mode","sessions");if(!dn(r))return e;let n=[];try{n=di(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():rt()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of n){let m=Bt(r,d);qd(m,o);try{let h=new o(m,{readonly:!0});try{if(t.sessionId){let p=h.prepare(`SELECT
538
557
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
539
558
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
540
559
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
541
- FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=f.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);h?.bytes&&(c+=Number(h.bytes))}catch{}}else if(t.projectDir){let p=f.prepare(`SELECT
560
+ FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);f?.bytes&&(c+=Number(f.bytes))}catch{}}else if(t.projectDir){let p=h.prepare(`SELECT
542
561
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
543
562
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
544
563
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
545
564
  FROM session_events
546
565
  WHERE session_id IN (
547
566
  SELECT session_id FROM session_meta WHERE project_dir = ?
548
- )`).get(t.projectDir);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=f.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
567
+ )`).get(t.projectDir);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let f=h.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
549
568
  FROM session_resume
550
569
  WHERE session_id IN (
551
570
  SELECT session_id FROM session_meta WHERE project_dir = ?
552
- )`).get(t.projectDir);h?.bytes&&(c+=Number(h.bytes))}catch{}}else{let p=f.prepare(`SELECT
571
+ )`).get(t.projectDir);f?.bytes&&(c+=Number(f.bytes))}catch{}}else{let p=h.prepare(`SELECT
553
572
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
554
573
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
555
574
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
556
- FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=f.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{f.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=VU(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let d=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:d}}function GU(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!tn(t.sessionsDir))return n;let o=[];try{o=Vs(t.sessionsDir).filter(d=>d.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let d of o){let l=Lt(t.sessionsDir,d);try{let m=new s(l,{readonly:!0});try{let f=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Ol(t){let e=BU({home:t?.home}),r=t?.loadDatabase??Qe,n={...WU,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!tn(c.sessionsDir))continue;let u=GU(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function Pl(t){return KU[t]??t}function ct(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function JU(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function $l(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function YU(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!$l(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=FU("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!$l(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!$l(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return $l(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function bT(t){let e=Cl();return e?t===e?"~":t.startsWith(e+HU)?"~"+t.slice(e.length):t:t}function XU(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,o=(h,g=2)=>h.toFixed(g),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),f=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${o(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${ct(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function QU(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],m=e.events*ET,f=Math.round((e.snapshotBytes??0)/4),p=m+f,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(r?.totalEvents??0)*ET,v=Math.round((r?.rescueBytes??0)/4),_=y+v,b=o?.lifetime?.totalSavedTokens??0,x=Math.max(_,b),P=o?.lifetime?.bytesReturned??0,E=o?.lifetime?.bytesAvoided??0,R=P+E>0?Math.max(1,Math.floor(P/4)):Math.max(1,Math.round(x*.02)),A=n?.totalBytes&&n.totalBytes>0?n.totalBytes:x*4,L=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,w=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,F=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,U=F>0?Math.max(1,Math.round((c-F)/864e5)):0,te=n?.totalSessions??r?.totalSessions??1,Ze=n?.perAdapter.filter(Be=>Be.isReal).length??0,ft;if(n&&Ze>=2)ft=`across ${Ze} AI tools`;else if(n&&Ze===1){let Be=n.perAdapter.find(ir=>ir.isReal);ft=`in ${Be?Pl(Be.name):"Claude Code"}`}else ft="in Claude Code";U>0?l.push(` Across ${U} days you ran ${xr(te)} conversations ${ft}.`):l.push(` You ran ${xr(te)} conversations ${ft}.`);let sr=U>0?A/U:0;l.push(` context-mode kept ${ct(A)} out of your context window \u2014 about ${ct(sr)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let Zn=e.firstEventMs&&e.firstEventMs>0?xT(e.firstEventMs,i,a):"";if(Zn?l.push(` This conversation started ${Zn} in ${bT(s)}.`):l.push(` This conversation lives in ${bT(s)}.`),l.push(` ${w}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Be=e.lastRescueMs&&e.lastRescueMs>0?xT(e.lastRescueMs,i,a):"",ir=Math.round(e.snapshotBytes/1024);Be?l.push(` On ${Be}, /compact fired \u2014 ${ir} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${ir} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let Fa=o?.conversation,Ua=Fa?.bytesAvoided??0,Xl=Fa?.bytesReturned??0;if(Ua+Xl===0)l.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),l.push("");else{let Be=Ua+Xl,ir=Math.max(1,Xl),ar=Math.max(1,Math.floor(Be/4)),Fr=Math.max(1,Math.floor(ir/4)),Ql=zn(ar,ar,32),TP=zn(Fr,ar,32),PP=(1-Fr/ar)*100,RP=Math.max(1,Math.round(ar/Fr));l.push(` Without context-mode ${ct(Be).padStart(8)} ${Ql} ${xr(ar).padStart(7)} tokens`),l.push(` With context-mode ${ct(ir).padStart(8)} ${TP} ${xr(Fr).padStart(7)} tokens`),l.push(` ${PP.toFixed(0)}% kept out of context \xB7 your AI ran ${RP}\xD7 longer before /compact fired`),l.push("")}if(e.byDay&&e.byDay.length>0){let Be=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${ct(L)} built up \u2014 ${Be} days, ${e.byDay.length} active:`),l.push(""),l.push(...tH(e.byDay,i,a))}l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),l.push("");let kP=e.byCategory.reduce((Be,ir)=>Be+ir.count,0).toLocaleString(i);l.push(` ${kP} things \u2014 files, errors, decisions, agent runs:`),l.push("");let wP=e.byCategory[0]?.count??1;for(let Be of e.byCategory)l.push(` ${Be.label.padEnd(26)} ${String(Be.count).padStart(5)} ${zn(Be.count,wP,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let k_=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",w_=F>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(F)):"",E_=r?.distinctProjects??0,EP=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${ct(L)} kept out \xB7 ${e.events.toLocaleString(i)} captures${k_?` \xB7 started ${k_}`:""}.`),l.push(` All your work: ${ct(A)} kept out \xB7 ${EP.toLocaleString(i)} captures across ${E_} project${E_===1?"":"s"}${w_?` \xB7 since ${w_}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...XU(A,x,U)),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),l.push(""),r&&r.autoMemoryCount>0){l.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Be=Object.entries(r.autoMemoryByPrefix).sort((ar,Fr)=>Fr[1]-ar[1]),ir=Be.length>0?Be[0][1]:1;for(let[ar,Fr]of Be){let Ql=CT[ar]??ar;l.push(` ${Ql.padEnd(26)} ${String(Fr).padStart(2)} ${zn(Fr,ir,20)}`)}}else l.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");l.push(""),l.push(""),l.push(" Your AI talks less, remembers more, costs less."),l.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),l.push("");let $P=u?`v${u}`:"context-mode";return l.push(` ${$P}`),u&&d&&d!=="unknown"&&TT(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),eH(l)}function eH(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function tH(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,f)=>m.ms-f.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let f=Math.round((m.ms-o.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[f]=p}let d=m=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},l=[];l.push(` ${d(o.ms)} ${u.join("")} ${d(s.ms)}`),l.push("");for(let m of n){let f=d(m.ms).padEnd(7),p=`${m.count} captures`,h=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${f} ${p}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function xT(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=l=>o.find(m=>m.type===l)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),d=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${d} (${r})`}function xr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Rl(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Il).toFixed(2)}`}function zn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function ST(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(h=>h.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";o.push(` All your work${h} \xB7 ${xr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${xr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${xr(h)} sessions`,y=a*256+r;o.push(` ${xr(a)} events \xB7 ${g} \xB7 ~${Rl(y)} saved lifetime`)}o.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Tl[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let m=l.slice(0,n),f=m.length>0?m[0].count:1;for(let h of m)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${zn(h.count,f,30)}`);let p=Math.max(0,l.length-n);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function kT(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=CT[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${zn(s,n,20)}`)}return e}function wT(t,e){let r=[],n=Rl(t),o=(e?.totalEvents??0)*256+t,s=Rl(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}function $T(t){if(!t)return[];let e=t.perAdapter.filter(o=>o.isReal),r=t.perAdapter.filter(o=>!o.isReal);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,d)=>d.dataBytes+d.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let d=u.dataBytes+u.rescueBytes,l=u.eventCount>0?xr(u.eventCount):"\u2014",m=ct(u.dataBytes),f=ct(d);n.push(` ${Pl(u.name).padEnd(o)}${l.padStart(s)}${m.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>Pl(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function Al(t,e,r,n){let o=[],s=JU(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(P=>P.isReal).length??0;if(d&&l>0){let P=d.totalSessions||i?.totalSessions||0,E=i?.firstEventMs??0,R=E>0?Math.max(1,Math.round((Date.now()-E)/864e5)):0,A=R>0?`Across ${R} day${R===1?"":"s"} `:"",L=P>0?`you ran ${xr(P)} conversation${P===1?"":"s"} `:"you ran ",w;if(l>=2)w=`across ${l} AI tools`;else{let F=d.perAdapter.find(U=>U.isReal);w=`in ${F?Pl(F.name):"Claude Code"}`}o.push(`${A}${L}${w}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let P=YU(),E=n?.cwd??process.cwd(),R=n?.now??Date.now(),A=n?.locale??P.locale,L=n?.tz??P.tz;return o.push(...QU({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:E,locale:A,tz:L,now:R,version:e,latestVersion:r})),o.join(`
557
- `)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),f=t.savings.total_bytes_returned,p=t.savings.total_calls,h=m+f,g=h>0?m/h*100:0,y=Math.round(m/4),v=f>0?Math.max(1,Math.round(h/Math.max(f,1))):0;if(m===0){o.push(`context-mode ${s} ${p} calls`),o.push(""),p===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${ct(f)} entered context | 0 tokens saved`),o.push(...ST(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),o.push(...$T(d)),o.push(...kT(i)),o.push(...wT(0,i)),o.push("");let P=e?`v${e}`:"context-mode";return o.push(P),e&&r&&r!=="unknown"&&TT(r,e)&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
558
- `)}o.push(`${xr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Rl(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${zn(h,h)}| ${ct(h)}`),o.push(`With context-mode |${zn(f,h)}| ${ct(f)}`),o.push(""),v>=2?o.push(`${ct(m)} kept out of your conversation \u2014 ${v}\xD7 longer sessions before compact.`):o.push(`${ct(m)} kept out of your conversation. Never entered context.`),o.push("");let _=[`${p} calls`];t.cache&&t.cache.hits>0&&_.push(`${t.cache.hits} cache hits (+${ct(t.cache.bytes_saved)})`),o.push(_.join(" \xB7 "));let b=t.savings.by_tool.filter(P=>P.calls>0);if(b.length>=2){o.push("");let P=b.map(E=>{let R=E.context_kb*1024,A=g<100?R/(1-g/100):R,L=Math.max(0,A-R);return{...E,returnedBytes:R,estimatedSaved:L}}).sort((E,R)=>R.estimatedSaved-E.estimatedSaved);for(let E of P){let R=E.tool.length>22?E.tool.slice(0,19)+"...":E.tool;o.push(` ${R.padEnd(22)} ${String(E.calls).padStart(4)} calls ${ct(E.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let P=a.filter(E=>E.median_concurrency!=null&&(E.max_concurrency??1)>1);if(P.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let E of P){let R=E.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${R.padEnd(22)} ${E.calls} batches \xB7 ${E.median_concurrency} typical, ${E.max_concurrency} peak`)}}}o.push(...ST(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:y})),o.push(...$T(d)),o.push(...kT(i)),o.push(...wT(y,i)),o.push("");let x=e?`v${e}`:"context-mode";return o.push(x),e&&r&&r!=="unknown"&&r!==e&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
559
- `)}var Tl,ZU,Ws,WU,CT,KU,Il,ET,OT=S(()=>{"use strict";ln();Tr();hn();Tl={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},ZU={file:"Restored after compact \u2014 no need to re-read",rule:"Your project instructions survive context resets",prompt:"Continues exactly where you left off",decision:"Applied automatically \u2014 won\u2019t ask again",task:"Picks up from where it stopped",error:"Tracked and monitored across compacts",git:"Branch, commit, and repo state preserved",env:"Runtime config carried forward",mcp:"Tool usage patterns remembered",subagent:"Delegation history preserved",skill:"Skill invocations tracked"},Ws=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){let c=[...s.concurrencies].sort((d,l)=>d-l),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((w,F)=>w+F,0),s=Object.values(e.calls).reduce((w,F)=>w+F,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,d=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),l=Array.from(d).sort().map(w=>({tool:w,calls:e.calls[w]||0,context_kb:Math.round((e.bytesReturned[w]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[w]||0)/4)})),f=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;if(e.cacheHits>0||e.cacheBytesSaved>0){let w=a+e.cacheBytesSaved,F=w/Math.max(o,1),U=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:U,total_with_cache:w,total_savings_ratio:F}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),v=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,_=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),b=_?!_.consumed:!1,x=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),P=new Map;for(let w of x){P.has(w.category)||P.set(w.category,new Set);let F=P.get(w.category);if(F.size<5){let U=w.data;w.category==="file"?U=w.data.split("/").pop()||w.data:(w.category==="prompt"||w.category==="user-prompt")&&(U=U.length>50?U.slice(0,47)+"...":U),U.length>40&&(U=U.slice(0,37)+"..."),F.add(U)}}let E=g.map(w=>({category:w.category,count:w.cnt,label:Tl[w.category]||w.category,preview:P.get(w.category)?Array.from(P.get(w.category)).join(", "):"",why:ZU[w.category]||"Survives context resets"})),R=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),L=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(w=>w.cnt>0).map(w=>({category:w.category,count:w.cnt,label:Tl[w.category]||w.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:l,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:f},continuity:{total_events:h,by_category:E,compact_count:v,resume_ready:b},projectMemory:{total_events:R.cnt,session_count:R.sessions,by_category:L}}}};WU={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};CT={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},KU={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};Il=15/1e6;ET=256});var aP={};Le(aP,{REGISTERED_CTX_TOOLS:()=>qT,__resetSuppressionDiagnosticForTests:()=>yH,browserOpenArgv:()=>iP,buildBatchNodeOptionsPrefix:()=>rP,buildFetchCode:()=>sP,classifyIp:()=>Da,currentAttribution:()=>Ln,emitSuppressionDiagnostic:()=>GT,extractSnippet:()=>y_,formatBatchQueryResults:()=>tP,getProjectDir:()=>Ut,killProcessOnPort:()=>v_,openBrowserSync:()=>p_,positionsFromHighlight:()=>eP,registerEmptyToolsListHandler:()=>KT,resolveSessionIdFromSessionDB:()=>JT,runBatchCommands:()=>nP,server:()=>ze,shouldSuppressMcpToolsForNativePluginHost:()=>VT,withProjectDirOverride:()=>bH});import{createRequire as HT}from"node:module";import{existsSync as $e,unlinkSync as Js,readdirSync as rH,readFileSync as Zl,writeFileSync as m_,renameSync as nH,rmSync as zl,mkdirSync as ZT,cpSync as oH,statSync as u_,symlinkSync as sH,lstatSync as iH}from"node:fs";import{execSync as IT,spawnSync as BT}from"node:child_process";import{join as Oe,dirname as kr,resolve as Ke,sep as aH,isAbsolute as cH}from"node:path";import{fileURLToPath as uH}from"node:url";import{homedir as Ys,tmpdir as f_,cpus as lH}from"node:os";import{request as dH}from"node:https";import{AsyncLocalStorage as pH}from"node:async_hooks";function VT(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let r=t.platform??Et().platform;if(r!=="opencode"&&r!=="kilo")return!1;let n=t.settings??fH(r);return hH(n)&&gH(n)}function mH(t){let e="",r=!1,n=!1,o=!1;for(let s=0;s<t.length;s++){let i=t[s],a=t[s+1];if(o){i==="*"&&a==="/"&&(o=!1,s++);continue}if(n){e+=i,n=!1;continue}if(i==="\\"){e+=i,n=r;continue}if(i==='"'){r=!r,e+=i;continue}if(!r&&i==="/"&&a==="/"){for(;s<t.length&&t[s]!==`
575
+ FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=hB(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}function yB(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!dn(t.sessionsDir))return n;let o=[];try{o=di(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let l of o){let d=Bt(t.sessionsDir,l);try{let m=new s(d,{readonly:!0});try{let h=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(n.eventCount+=Number(h.cnt??0),n.dataBytes+=Number(h.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let f=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<n.firstMs&&(n.firstMs=f)}if(p?.mx){let f=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>n.lastMs&&(n.lastMs=f)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of p)f.p&&i.add(f.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of p)f.s&&a.add(f.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Kl(t){let e=mB({home:t?.home}),r=t?.loadDatabase??rt,n={...gB,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!dn(c.sessionsDir))continue;let u=yB(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function ql(t){return _B[t]??t}function dt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function bB(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function Bl(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function xB(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Bl(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=uB("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!Bl(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!Bl(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return Bl(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function lP(t){let e=Wl();return e?t===e?"~":t.startsWith(e+dB)?"~"+t.slice(e.length):t:t}function vB(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*Xa(),o=(y,_=2)=>y.toFixed(_),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),h=(e*.8/1e6).toFixed(2),p=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,f=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return p&&f?g.push(` $${o(n)} of ${f} tokens your team didn't burn.`):p?g.push(` $${o(n)} of tokens your team didn't burn.`):g.push(` $${o(n)} of Opus 4 tokens your team didn't burn.`),g.push(` context-mode kept ${dt(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function SB(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],m=e.events*hP,h=Math.round((e.snapshotBytes??0)/4),p=m+h,f=o?.conversation?.totalSavedTokens??0,g=Math.max(p,f),y=(r?.totalEvents??0)*hP,_=Math.round((r?.rescueBytes??0)/4),b=y+_,v=o?.lifetime?.totalSavedTokens??0,E=Math.max(b,v),C=o?.lifetime?.bytesReturned??0,x=o?.lifetime?.bytesAvoided??0,k=C+x>0?Math.max(1,Math.floor(C/4)):Math.max(1,Math.round(E*.02)),P=n?.totalBytes&&n.totalBytes>0?n.totalBytes:E*4,N=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,R=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,O=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,F=O>0?Math.max(1,Math.round((c-O)/864e5)):0,K=n?.totalSessions??r?.totalSessions??1,ge=n?.perAdapter.filter(Ze=>Ze.isReal).length??0,We;if(n&&ge>=2)We=`across ${ge} AI tools`;else if(n&&ge===1){let Ze=n.perAdapter.find(pr=>pr.isReal);We=`in ${Ze?ql(Ze.name):"Claude Code"}`}else We="in Claude Code";F>0?d.push(` Across ${F} days you ran ${wr(K)} conversations ${We}.`):d.push(` You ran ${wr(K)} conversations ${We}.`);let _t=F>0?P/F:0;d.push(` context-mode kept ${dt(P)} out of your context window \u2014 about ${dt(_t)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Pr=e.firstEventMs&&e.firstEventMs>0?dP(e.firstEventMs,i,a):"";if(Pr?d.push(` This conversation started ${Pr} in ${lP(s)}.`):d.push(` This conversation lives in ${lP(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ze=e.lastRescueMs&&e.lastRescueMs>0?dP(e.lastRescueMs,i,a):"",pr=Math.round(e.snapshotBytes/1024);Ze?d.push(` On ${Ze}, /compact fired \u2014 ${pr} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${pr} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let ic=o?.conversation,ac=ic?.bytesAvoided??0,hd=ic?.bytesReturned??0;if(ac+hd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ze=ac+hd,pr=Math.max(1,hd),mr=Math.max(1,Math.floor(Ze/4)),Gr=Math.max(1,Math.floor(pr/4)),gd=Wn(mr,mr,32),DR=Wn(Gr,mr,32),MR=(1-Gr/mr)*100,jR=Math.max(1,Math.round(mr/Gr));d.push(` Without context-mode ${dt(Ze).padStart(8)} ${gd} ${wr(mr).padStart(7)} tokens`),d.push(` With context-mode ${dt(pr).padStart(8)} ${DR} ${wr(Gr).padStart(7)} tokens`),d.push(` ${MR.toFixed(0)}% kept out of context \xB7 your AI ran ${jR}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ze=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${dt(N)} built up \u2014 ${Ze} days, ${e.byDay.length} active:`),d.push(""),d.push(...wB(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let OR=e.byCategory.reduce((Ze,pr)=>Ze+pr.count,0).toLocaleString(i);d.push(` ${OR} things \u2014 files, errors, decisions, agent runs:`),d.push("");let IR=e.byCategory[0]?.count??1;for(let Ze of e.byCategory)d.push(` ${Ze.label.padEnd(26)} ${String(Ze.count).padStart(5)} ${Wn(Ze.count,IR,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let nb=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",ob=O>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(O)):"",sb=r?.distinctProjects??0,AR=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${dt(N)} kept out \xB7 ${e.events.toLocaleString(i)} captures${nb?` \xB7 started ${nb}`:""}.`),d.push(` All your work: ${dt(P)} kept out \xB7 ${AR.toLocaleString(i)} captures across ${sb} project${sb===1?"":"s"}${ob?` \xB7 since ${ob}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...vB(P,E,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Ze=Object.entries(r.autoMemoryByPrefix).sort((mr,Gr)=>Gr[1]-mr[1]),pr=Ze.length>0?Ze[0][1]:1;for(let[mr,Gr]of Ze){let gd=vP[mr]??mr;d.push(` ${gd.padEnd(26)} ${String(Gr).padStart(2)} ${Wn(Gr,pr,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let NR=u?`v${u}`:"context-mode";return d.push(` ${NR}`),u&&l&&l!=="unknown"&&_P(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),kB(d)}function kB(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function wB(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,h)=>m.ms-h.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let h=Math.round((m.ms-o.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[h]=p}let l=m=>{let h=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${p} ${f}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let m of n){let h=l(m.ms).padEnd(7),p=`${m.count} captures`,f=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";d.push(` ${h} ${p}${f}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function dP(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=d=>o.find(m=>m.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function wr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Xa(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 15/1e6}function Vl(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Xa()).toFixed(2)}`}function Wn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function pP(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(f=>f.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let f=i>=2?" everywhere":"";o.push(` All your work${f} \xB7 ${wr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${wr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&r>0?1:c,g=f===1?"1 session":`${wr(f)} sessions`,y=a*256+r;o.push(` ${wr(a)} events \xB7 ${g} \xB7 ~${Vl(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:Zl[f]||f})).sort((f,g)=>g.count-f.count):d=(t.by_category??[]).filter(f=>f&&f.count>0);let m=d.slice(0,n),h=m.length>0?m[0].count:1;for(let f of m)o.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Wn(f.count,h,30)}`);let p=Math.max(0,d.length-n);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function mP(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=vP[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Wn(s,n,20)}`)}return e}function fP(t,e){let r=[],n=Vl(t),o=(e?.totalEvents??0)*256+t,s=Vl(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}function gP(t){if(!t)return[];let e=[],r=[];for(let o of t.perAdapter)(o.isReal?e:r).push(o);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?wr(u.eventCount):"\u2014",m=dt(u.dataBytes),h=dt(l);n.push(` ${ql(u.name).padEnd(o)}${d.padStart(s)}${m.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>ql(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function yP(t,e){let r=[];if(t.cache){let n=(t.cache.hit_rate*100).toFixed(1);r.push(`cache.hit_rate: ${n}% (${t.cache.hits} hits / ${t.cache.misses} misses)`)}return e&&(r.push(`index.total_chunks: ${e.totalChunks}`),r.push(`index.total_sources: ${e.totalSources}`),e.lastIndexedAt&&r.push(`index.last_indexed_at: ${e.lastIndexedAt}`)),r.length===0?[]:["","## Observability",...r]}function Gl(t,e,r,n){let o=[],s=bB(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(C=>C.isReal).length??0;if(l&&d>0){let C=l.totalSessions||i?.totalSessions||0,x=i?.firstEventMs??0,k=x>0?Math.max(1,Math.round((Date.now()-x)/864e5)):0,P=k>0?`Across ${k} day${k===1?"":"s"} `:"",N=C>0?`you ran ${wr(C)} conversation${C===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let O=l.perAdapter.find(F=>F.isReal);R=`in ${O?ql(O.name):"Claude Code"}`}o.push(`${P}${N}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let C=xB(),x=n?.cwd??process.cwd(),k=n?.now??Date.now(),P=n?.locale??C.locale,N=n?.tz??C.tz;return o.push(...SB({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:x,locale:P,tz:N,now:k,version:e,latestVersion:r})),o.push(...yP(t,n?.indexState)),o.join(`
576
+ `)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,p=t.savings.total_calls,f=m+h,g=f>0?m/f*100:0,y=Math.round(m/4),_=h>0?Math.max(1,Math.round(f/Math.max(h,1))):0;if(m===0){o.push(`context-mode ${s} ${p} calls`),o.push(""),p===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${dt(h)} entered context | 0 tokens saved`),o.push(...pP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...gP(l)),o.push(...mP(i)),o.push(...fP(0,i)),o.push("");let C=e?`v${e}`:"context-mode";return o.push(C),e&&r&&r!=="unknown"&&_P(r,e)&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
577
+ `)}o.push(`${wr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Vl(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${Wn(f,f)}| ${dt(f)}`),o.push(`With context-mode |${Wn(h,f)}| ${dt(h)}`),o.push(""),_>=2?o.push(`${dt(m)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${dt(m)} kept out of your conversation. Never entered context.`),o.push("");let b=[`${p} calls`];t.cache&&t.cache.hits>0&&b.push(`${t.cache.hits} cache hits (+${dt(t.cache.bytes_saved)})`),o.push(b.join(" \xB7 "));let v=t.savings.by_tool.filter(C=>C.calls>0);if(v.length>=2){o.push("");let C=v.map(x=>{let k=x.context_kb*1024,P=g<100?k/(1-g/100):k,N=Math.max(0,P-k);return{...x,returnedBytes:k,estimatedSaved:N}}).sort((x,k)=>k.estimatedSaved-x.estimatedSaved);for(let x of C){let k=x.tool.length>22?x.tool.slice(0,19)+"...":x.tool;o.push(` ${k.padEnd(22)} ${String(x.calls).padStart(4)} calls ${dt(x.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let C=a.filter(x=>x.median_concurrency!=null&&(x.max_concurrency??1)>1);if(C.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let x of C){let k=x.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${k.padEnd(22)} ${x.calls} batches \xB7 ${x.median_concurrency} typical, ${x.max_concurrency} peak`)}}}o.push(...pP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...gP(l)),o.push(...mP(i)),o.push(...fP(y,i)),o.push(...yP(t,n?.indexState)),o.push("");let E=e?`v${e}`:"context-mode";return o.push(E),e&&r&&r!=="unknown"&&r!==e&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
578
+ `)}var Zl,pB,pi,gB,vP,_B,lX,hP,SP=S(()=>{"use strict";bn();Jt();kn();Zl={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},pB={file:"Restored after compact \u2014 no need to re-read",rule:"Your project instructions survive context resets",prompt:"Continues exactly where you left off",decision:"Applied automatically \u2014 won\u2019t ask again",task:"Picks up from where it stopped",error:"Tracked and monitored across compacts",git:"Branch, commit, and repo state preserved",env:"Runtime config carried forward",mcp:"Tool usage patterns remembered",subagent:"Delegation history preserved",skill:"Skill invocations tracked"},pi=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((O,F)=>O+F,0),s=Object.values(e.calls).reduce((O,F)=>O+F,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(O=>({tool:O,calls:e.calls[O]||0,context_kb:Math.round((e.bytesReturned[O]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[O]||0)/4)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),p,f=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||f>0){let O=a+e.cacheBytesSaved,F=O/Math.max(o,1),K=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ge=e.cacheHits+f,We=ge>0?e.cacheHits/ge:0;p={hits:e.cacheHits,misses:f,hit_rate:We,bytes_saved:e.cacheBytesSaved,ttl_hours_left:K,total_with_cache:O,total_savings_ratio:F}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,v=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),E=v?!v.consumed:!1,C=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),x=new Map;for(let O of C){x.has(O.category)||x.set(O.category,new Set);let F=x.get(O.category);if(F.size<5){let K=O.data;O.category==="file"?K=O.data.split("/").pop()||O.data:(O.category==="prompt"||O.category==="user-prompt")&&(K=K.length>50?K.slice(0,47)+"...":K),K.length>40&&(K=K.slice(0,37)+"..."),F.add(K)}}let k=y.map(O=>({category:O.category,count:O.cnt,label:Zl[O.category]||O.category,preview:x.get(O.category)?Array.from(x.get(O.category)).join(", "):"",why:pB[O.category]||"Survives context resets"})),P=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),R=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(O=>O.cnt>0).map(O=>({category:O.category,count:O.cnt,label:Zl[O.category]||O.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:h},continuity:{total_events:g,by_category:k,compact_count:b,resume_ready:E},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:R}}}};gB={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};vP={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},_B={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};lX=15/1e6;hP=256});var tR={};we(tR,{REGISTERED_CTX_TOOLS:()=>LP,__resetSuppressionDiagnosticForTests:()=>LB,browserOpenArgv:()=>eR,buildBatchNodeOptionsPrefix:()=>KP,buildFetchCode:()=>QP,classifyIp:()=>ec,currentAttribution:()=>Kn,emitSuppressionDiagnostic:()=>HP,extractSnippet:()=>q_,formatBatchQueryResults:()=>WP,getProjectDir:()=>Lt,killProcessOnPort:()=>G_,openBrowserSync:()=>F_,positionsFromHighlight:()=>VP,registerEmptyToolsListHandler:()=>UP,resolveSessionIdFromSessionDB:()=>BP,runBatchCommands:()=>XP,server:()=>Fe,shouldSuppressMcpToolsForNativePluginHost:()=>zP,withProjectDirOverride:()=>HB});import{createRequire as AP}from"node:module";import{existsSync as ke,unlinkSync as hi,readdirSync as NP,readFileSync as tc,writeFileSync as H_,renameSync as EB,rmSync as td,mkdirSync as DP,cpSync as $B,statSync as rd,symlinkSync as TB,lstatSync as MP,realpathSync as PB}from"node:fs";import{execSync as kP,spawnSync as jP}from"node:child_process";import{join as Ce,dirname as Zt,resolve as Ve,sep as M_,isAbsolute as RB}from"node:path";import{fileURLToPath as CB}from"node:url";import{homedir as gi,tmpdir as U_,cpus as OB}from"node:os";import{request as IB}from"node:https";import{AsyncLocalStorage as AB}from"node:async_hooks";function zP(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let r=t.platform??vt().platform;if(r!=="opencode"&&r!=="kilo")return!1;let n=t.settings??DB(r);return MB(n)&&jB(n)}function NB(t){let e="",r=!1,n=!1,o=!1;for(let s=0;s<t.length;s++){let i=t[s],a=t[s+1];if(o){i==="*"&&a==="/"&&(o=!1,s++);continue}if(n){e+=i,n=!1;continue}if(i==="\\"){e+=i,n=r;continue}if(i==='"'){r=!r,e+=i;continue}if(!r&&i==="/"&&a==="/"){for(;s<t.length&&t[s]!==`
560
579
  `;)s++;s<t.length&&(e+=`
561
- `);continue}if(!r&&i==="/"&&a==="*"){o=!0,s++;continue}e+=i}return e.replace(/,(\s*[}\]])/g,"$1")}function fH(t){let e=t==="kilo"?"kilo":"opencode",r=[Ke(`${e}.json`),Ke(`${e}.jsonc`),Ke(`.${e}`,`${e}.json`),Ke(`.${e}`,`${e}.jsonc`),Oe(Ys(),".config",e,`${e}.json`),Oe(Ys(),".config",e,`${e}.jsonc`)];for(let n of r)try{if(!$e(n))continue;return JSON.parse(mH(Zl(n,"utf8")))}catch{}return null}function hH(t){let e=t?.plugin;return Array.isArray(e)&&e.some(r=>typeof r=="string"&&r.includes("context-mode"))}function gH(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function GT(t={}){if(l_)return;l_=!0;let e=t.write??(n=>{process.stderr.write(n)}),r=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${r}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
562
- `)}function yH(){l_=!1}function KT(t=ze){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Ss,async()=>({tools:[]}))}function vH(t,e){return async r=>{try{return await e(r)}catch(n){let o=EH(n);if(o)try{return G(t,o)}catch(s){if(s instanceof cr)return o;throw s}throw n}}}async function bH(t,e){let r=typeof t=="string"?{projectDir:t}:t;return h_.run(r,e)}function Ln(){let t=h_.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??JT();if(e)return{sessionId:e}}function JT(t){let e=Date.now();if(!t?.bypassCache&&Nl&&e-Nl.checkedAt<2e3)return Nl.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??Xe(),o=pi({projectDir:r,sessionsDir:n});if(!$e(o))return;let s=Qe(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(Nl={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function xH(t){try{let e=Xe();if(!$e(e))return;let r=rH(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let o=Oe(e,n);try{t.index({path:o,source:"session-events",attribution:Ln()}),Js(o)}catch{}}}catch{}}async function SH(){if(Fn)return Fn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(yn(),bc)),e=Et();return await t(e.platform)}catch{return null}}function Gs(){if(Fn)return Fn.getSessionDir();try{let t=Et(),e=yi(t.platform);if(e)return Sd({configDir:Oe(...e),configDirEnv:kH(e)})}catch{}return Sd({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function kH(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Xe(){return mn(pn(Gs))}function Ut(){let t=h_.getStore();if(t)return t.projectDir;let e,r,n;try{let o=Et().platform;r=o,o==="claude-code"&&(e=Oe(Ys(),".claude","projects")),o==="codex"&&(n=process.env.CODEX_HOME??Oe(Ys(),".codex"))}catch{}return _T({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:r,codexHome:n})}function wH(t){return cH(t)?t:Ke(Ut(),t)}function Na(){return pi({projectDir:Ut(),sessionsDir:Xe()})}function Ll(){let t=mn(qo(Gs));return hv({projectDir:Ut(),contentDir:t})}function Un(){if(!Sr){let t=Ll();Sr=new xl(t),Sr.setDenyChecker(e=>{try{let r=Ut(),n=Sl("Read",r);return kl(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=kr(Ll());Ky(e,14),Sr.cleanupStaleSources(14);let r=Oe(Ys(),".context-mode","content");$e(r)&&Ky(r,0)}catch{}Gy()}return xH(Sr),Sr}function EH(t){return t instanceof cr?{content:[{type:"text",text:li(t)}],isError:!0}:null}async function NT(){return new Promise(t=>{let e=dH("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function PH(){let t=Fn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function RH(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function CH(){return!on||on==="unknown"?!1:RH(on,nn)}function OH(){if(!CH())return!1;let t=Date.now();if(Dl>=$H){if(t-AT<TH)return!1;Dl=0}return Dl===0&&(AT=t),Dl++,!0}function IH(){if(!DT){DT=!0;try{let t=qe(),e=Ke(t,"plugins","installed_plugins.json");if(!$e(e))return;let r=JSON.parse(Zl(e,"utf-8")),n=Ke(t,"plugins","cache"),o=$e(Ke(Ft,"package.json"))?Ft:kr(Ft);for(let[s,i]of Object.entries(r.plugins??{}))if(s==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||$e(c)||!Ke(c).startsWith(n+aH))continue;try{iH(c).isSymbolicLink()&&Js(c)}catch{}let u=kr(c);$e(u)||ZT(u,{recursive:!0}),$e(o)&&sH(o,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function G(t,e){if(IH(),OH()&&e.content.length>0){let n=PH();e.content[0].text=`\u26A0\uFE0F context-mode v${nn} outdated \u2192 v${on} available. Upgrade: ${n}
580
+ `);continue}if(!r&&i==="/"&&a==="*"){o=!0,s++;continue}e+=i}return e.replace(/,(\s*[}\]])/g,"$1")}function DB(t){let e=t==="kilo"?"kilo":"opencode",r=[Ve(`${e}.json`),Ve(`${e}.jsonc`),Ve(`.${e}`,`${e}.json`),Ve(`.${e}`,`${e}.jsonc`),Ce(gi(),".config",e,`${e}.json`),Ce(gi(),".config",e,`${e}.jsonc`)];for(let n of r)try{if(!ke(n))continue;return JSON.parse(NB(tc(n,"utf8")))}catch{}return null}function MB(t){let e=t?.plugin;return Array.isArray(e)&&e.some(r=>typeof r=="string"&&r.includes("context-mode"))}function jB(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function HP(t={}){if(j_)return;j_=!0;let e=t.write??(n=>{process.stderr.write(n)}),r=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${r}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
581
+ `)}function LB(){j_=!1}function UP(t=Fe){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Us,async()=>({tools:[]}))}function FB(t,e){return async r=>{try{return await e(r)}catch(n){let o=VB(n);if(o)try{return W(t,o)}catch(s){if(s instanceof Kt)return o;throw s}throw n}}}async function HB(t,e){let r=typeof t=="string"?{projectDir:t}:t;return B_.run(r,e)}function Kn(){let t=B_.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??BP();if(e)return{sessionId:e}}function BP(t){let e=Date.now();if(!t?.bypassCache&&Jl&&e-Jl.checkedAt<2e3)return Jl.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??Be(),o=cs({projectDir:r,sessionsDir:n});if(!ke(o))return;let s=rt(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(Jl={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function UB(t){try{let e=Be();if(!ke(e))return;let r=NP(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let o=Ce(e,n);try{t.index({path:o,source:"session-events",attribution:Kn()}),hi(o)}catch{}}}catch{}}async function BB(){if($r)return $r;try{let{getAdapter:t}=await Promise.resolve().then(()=>($n(),Lc)),e=vt();return await t(e.platform)}catch{return null}}function mi(){if($r)return $r.getSessionDir();try{let t=vt(),e=Mi(t.platform);if(e)return $c({configDir:Ce(...e),configDirEnv:ZB(e)})}catch{}return $c({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function ZB(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Be(){return Ir(Jr(mi))}function Lt(){let t=B_.getStore();if(t)return t.projectDir;let e,r,n;try{let o=vt().platform;r=o,o==="claude-code"&&(e=Ce(gi(),".claude","projects")),o==="codex"&&(n=process.env.CODEX_HOME??Ce(gi(),".codex"))}catch{}return cP({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:r,codexHome:n})}function qB(t){return RB(t)?t:Ve(Lt(),t)}function Qa(){return cs({projectDir:Lt(),sessionsDir:Be()})}function nd(){let t=Ir(vn(mi));return Bd({projectDir:Lt(),contentDir:t})}function Vr(){if(!Er){let t=nd();Er=new vs(t),Er.setDenyChecker(e=>{try{let r=Lt(),n=lo("Read",r);return po(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=Zt(nd());Kp(e,14),Er.cleanupStaleSources(14);let r=Ce(gi(),".context-mode","content");ke(r)&&Kp(r,0)}catch{}Wp()}return UB(Er),Er}function VB(t){return t instanceof Kt?{content:[{type:"text",text:is(t)}],isError:!0}:null}async function EP(){return new Promise(t=>{let e=IB("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function GB(){let t=$r?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function JB(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function XB(){return!fn||fn==="unknown"?!1:JB(fn,mn)}function YB(){if(!XB())return!1;let t=Date.now();if(Xl>=WB){if(t-wP<KB)return!1;Xl=0}return Xl===0&&(wP=t),Xl++,!0}function QB(){if(!$P){$P=!0;try{let t=qe(),e=Ve(t,"plugins","installed_plugins.json");if(!ke(e))return;let r=JSON.parse(tc(e,"utf-8")),n=Ve(t,"plugins","cache"),o=ke(Ve(qt,"package.json"))?qt:Zt(qt);for(let[s,i]of Object.entries(r.plugins??{}))if(s==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||ke(c)||!Ve(c).startsWith(n+M_))continue;try{MP(c).isSymbolicLink()&&hi(c)}catch{}let u=Zt(c);ke(u)||DP(u,{recursive:!0}),ke(o)&&TB(o,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(QB(),YB()&&e.content.length>0){let n=GB();e.content[0].text=`\u26A0\uFE0F context-mode v${mn} outdated \u2192 v${fn} available. Upgrade: ${n}
563
582
 
564
- `+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+r,Fl(),setImmediate(()=>cT(Na(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>nT({sessionDbPath:Na(),toolName:t,bytesReturned:r})),e}function wr(t,e="unknown"){ie.bytesIndexed+=t,Fl(),t>0&&setImmediate(()=>oT({sessionDbPath:Na(),source:e,bytesAvoided:t}))}function YT(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=mn(ui(Gs));return Oe(e,`stats-${t}.json`)}function Fl(){let t=Date.now();if(!(t-d_<AH)){d_=t;try{let e=Object.values(ie.bytesReturned).reduce((l,m)=>l+m,0),r=Object.values(ie.calls).reduce((l,m)=>l+m,0),n=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=n+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(n/4),a=Ml?.tokens??0;if(!Ml||t-Ml.computedAt>DH)try{a=(Oa({sessionsDir:Xe()})?.totalEvents??0)*MH,Ml={tokens:a,computedAt:t}}catch{}let c={schemaVersion:NH,version:nn,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:n,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*Il).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Il).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ie.calls,...ie.bytesReturned}).map(l=>[l,{calls:ie.calls[l]||0,bytes:ie.bytesReturned[l]||0}]))},u=YT(),d=`${u}.tmp`;m_(d,JSON.stringify(c)),nH(d,u)}catch{}}}function g_(t,e){try{let r=Xy(process.env.CLAUDE_PROJECT_DIR),n=Qy(t,r);if(n.decision==="deny")return G(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function XT(t,e,r){try{let n=G$(t,e);if(n.length===0)return null;let o=Xy(process.env.CLAUDE_PROJECT_DIR);for(let s of n){let i=Qy(s,o);if(i.decision==="deny")return G(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function QT(t,e){try{let r=Ut(),n=Sl("Read",r),o=kl(t,n,process.platform==="win32",r);if(o.denied)return G(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function eP(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===LH){for(e.push(r),n++;n<t.length&&t[n]!==FH;)r++,n++;n<t.length&&n++}else r++,n++;return e}function y_(t,e,r=1500,n){if(t.length<=r)return t;let o=[];if(n)for(let u of eP(n))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(l=>l.length>2),d=t.toLowerCase();for(let l of u){let m=d.indexOf(l);for(;m!==-1;)o.push(m),m=d.indexOf(l,m+1)}}if(o.length===0)return t.slice(0,r)+`
565
- \u2026`;o.sort((u,d)=>u-d);let s=300,i=[];for(let u of o){let d=Math.max(0,u-s),l=Math.min(t.length,u+s);i.length>0&&d<=i[i.length-1][1]?i[i.length-1][1]=l:i.push([d,l])}let a=[],c=0;for(let[u,d]of i){if(c>=r)break;let l=t.slice(u,Math.min(d,u+(r-c)));a.push((u>0?"\u2026":"")+l+(d<t.length?"\u2026":"")),c+=l.length}return a.join(`
583
+ `+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+r,od(),setImmediate(()=>GT(Qa(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>ZT({sessionDbPath:Qa(),toolName:t,bytesReturned:r})),e}function Tr(t,e="unknown"){ie.bytesIndexed+=t,od(),t>0&&setImmediate(()=>qT({sessionDbPath:Qa(),source:e,bytesAvoided:t}))}function sZ(t){return oZ.test(t)?t:`pid-${process.ppid}`}function ZP(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=sZ(t),r=Ir(ss(mi));return Ce(r,`stats-${e}.json`)}function od(){let t=Date.now();if(!(t-L_<eZ)){L_=t;try{let e=Object.values(ie.bytesReturned).reduce((d,m)=>d+m,0),r=Object.values(ie.calls).reduce((d,m)=>d+m,0),n=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=n+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(n/4),a=Yl?.tokens??0;if(!Yl||t-Yl.computedAt>rZ)try{a=(Ga({sessionsDir:Be()})?.totalEvents??0)*nZ,Yl={tokens:a,computedAt:t}}catch{}let c={schemaVersion:tZ,version:mn,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:n,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*Xa()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Xa()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ie.calls,...ie.bytesReturned}).map(d=>[d,{calls:ie.calls[d]||0,bytes:ie.bytesReturned[d]||0}]))},u=ZP(),l=`${u}.tmp`;H_(l,JSON.stringify(c)),EB(l,u)}catch{}}}function Z_(t,e){try{let r=Xp(process.env.CLAUDE_PROJECT_DIR),n=Yp(t,r);if(n.decision==="deny")return W(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function qP(t,e,r){try{let n=Vv(t,e);if(n.length===0)return null;let o=Xp(process.env.CLAUDE_PROJECT_DIR);for(let s of n){let i=Yp(s,o);if(i.decision==="deny")return W(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function z_(t,e){try{let r=Lt(),n=lo("Read",r),o=po(t,n,process.platform==="win32",r);if(o.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function VP(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===cZ){for(e.push(r),n++;n<t.length&&t[n]!==uZ;)r++,n++;n<t.length&&n++}else r++,n++;return e}function q_(t,e,r=1500,n){if(t.length<=r)return t;let o=[];if(n)for(let u of VP(n))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let m=l.indexOf(d);for(;m!==-1;)o.push(m),m=l.indexOf(d,m+1)}}if(o.length===0)return t.slice(0,r)+`
584
+ \u2026`;o.sort((u,l)=>u-l);let s=300,i=[];for(let u of o){let l=Math.max(0,u-s),d=Math.min(t.length,u+s);i.length>0&&l<=i[i.length-1][1]?i[i.length-1][1]=d:i.push([l,d])}let a=[],c=0;for(let[u,l]of i){if(c>=r)break;let d=t.slice(u,Math.min(l,u+(r-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
566
585
 
567
- `)}function tP(t,e,r,n=80*1024){let o=[],s=0;for(let i of e){if(s>n){o.push(`## ${i}
568
- (output cap reached \u2014 use ctx_search(queries: ["${i}"]) for details)
569
- `);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(o.push(`## ${i}`),o.push(""),a.length>0){for(let c of a){let u=y_(c.content,i,3e3,c.highlighted);o.push(`### ${c.title}`),o.push(u),o.push(""),s+=u.length+c.title.length}continue}o.push("No matching sections found."),o.push("")}return o.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),o}function UH(t){return`'${t.replace(/'/g,"'\\''")}'`}function HH(t){return`'${t.replace(/'/g,"''")}'`}function rP(t,e){let r=`--require ${e}`,n=t.toLowerCase(),o=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${HH(r)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${UH(r)} `}function MT(t,e,r){let n=e||"(no output)",o=n.matchAll(/__CM_FS__:(\d+)/g),s=0;for(let i of o)s+=parseInt(i[1]);return s>0&&(r?.(s),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
586
+ `)}function WP(t,e,r,n=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:r;for(let c of e){if(i>n){s.push(`## ${c}
587
+ (output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
588
+ `);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=q_(l.content,c,3e3,l.highlighted);s.push(`### ${l.title}`),s.push(d),s.push(""),i+=d.length+l.title.length}continue}s.push("No matching sections found."),s.push("")}return o==="global"?s.push(`
589
+ > **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function lZ(t){return`'${t.replace(/'/g,"'\\''")}'`}function dZ(t){return`'${t.replace(/'/g,"''")}'`}function KP(t,e){let r=`--require ${e}`,n=t.toLowerCase(),o=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${dZ(r)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${lZ(r)} `}function GP(t){let e=t.replace(/\s+/g," ").trim();return e.length<=TP?e:e.slice(0,TP)+"\u2026"}function pZ(t){return t.length<=PP?t:t.slice(0,PP)+`
590
+ \u2026 (truncated)`}function JP(t,e,r){let n=r?`path=${r}
591
+ `:"",o=`\`\`\`${t}
592
+ ${pZ(e)}
593
+ \`\`\``;return`${n}${o}
570
594
 
571
- ${n}
572
- `}function jT(t){let e=t.stdout||"",r=t.stderr||"";return r?e?`${e}${e.endsWith(`
595
+ `}function RP(t,e,r,n){let o=r||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(n?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=GP(e);return`# ${t}
596
+
597
+ $ ${a}
598
+
599
+ ${o}
600
+ `}function CP(t){let e=t.stdout||"",r=t.stderr||"";return r?e?`${e}${e.endsWith(`
573
601
  `)?"":`
574
- `}${r}`:r:e}async function nP(t,e,r){let{timeout:n,concurrency:o,nodeOptsPrefix:s,onFsBytes:i}=e;if(o<=1){let l=[],m=Date.now(),f=!1;for(let p=0;p<t.length;p++){let h=t[p],g;if(n!==void 0){let v=Date.now()-m,_=n-v;if(_<=0){l.push(`# ${h.label}
602
+ `}${r}`:r:e}async function XP(t,e,r){let{timeout:n,concurrency:o,nodeOptsPrefix:s,onFsBytes:i}=e;if(o<=1){let d=[],m=Date.now(),h=!1;for(let p=0;p<t.length;p++){let f=t[p],g;if(n!==void 0){let _=Date.now()-m,b=n-_;if(b<=0){d.push(`# ${f.label}
575
603
 
576
604
  (skipped \u2014 batch timeout exceeded)
577
- `),f=!0;continue}g=_}let y=await r.execute({language:"shell",code:`${s}${h.command}`,timeout:g});if(l.push(MT(h.label,jT(y),i)),y.timedOut){f=!0;for(let v=p+1;v<t.length;v++)l.push(`# ${t[v].label}
605
+ `),h=!0;continue}g=b}let y=await r.execute({language:"shell",code:`${s}${f.command}`,timeout:g});if(d.push(RP(f.label,f.command,CP(y),i)),y.timedOut){h=!0;for(let _=p+1;_<t.length;_++)d.push(`# ${t[_].label}
578
606
 
579
607
  (skipped \u2014 batch timeout exceeded)
580
- `);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${s}${l.command}`,timeout:n}),f=MT(l.label,jT(m),i);return{output:m.timedOut?f.replace(/\n$/,"")+`
608
+ `);break}}return{outputs:d,timedOut:h}}let a=t.map(d=>({run:async()=>{let m=await r.execute({language:"shell",code:`${s}${d.command}`,timeout:n}),h=RP(d.label,d.command,CP(m),i);return{output:m.timedOut?h.replace(/\n$/,"")+`
581
609
  (timed out after ${n??"?"}ms)
582
- `:f,timedOut:!!m.timedOut}}})),{settled:c}=await By(a,{concurrency:o}),u=new Array(t.length),d=!1;for(let l=0;l<c.length;l++){let m=c[l];if(m.status==="fulfilled")u[l]=m.value.output,m.value.timedOut&&(d=!0);else{let f=m.reason instanceof Error?m.reason.message:String(m.reason);u[l]=`# ${t[l].label}
583
-
584
- (executor error: ${f})
585
- `}}return{outputs:u,timedOut:d}}function oP(t,e){let r=Un();wr(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:Ln()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
586
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function Ks(t,e,r,n=5){let o=t.split(`
587
- `).length,s=Buffer.byteLength(t),i=Un(),a=i.indexPlainText(t,r,void 0,Ln()),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to explore the indexed content."),l.join(`
588
- `)}let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let l of c){let m=l.content.split(`
589
- `)[0].slice(0,120);d.push(` - ${l.title}: ${m}`)}return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),d.join(`
590
- `)}function ql(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function __(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function BH(t){let e=ql(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function qH(){return a_||(a_=HT(import.meta.url).resolve("turndown")),a_}function VH(){return c_||(c_=HT(import.meta.url).resolve("turndown-plugin-gfm")),c_}function sP(t,e){let r=JSON.stringify(qH()),n=JSON.stringify(VH()),o=JSON.stringify(e),s=Da.toString(),i=Da.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
610
+ `:h,timedOut:!!m.timedOut}}})),{settled:c}=await k_(a,{concurrency:o}),u=new Array(t.length),l=!1;for(let d=0;d<c.length;d++){let m=c[d];if(m.status==="fulfilled")u[d]=m.value.output,m.value.timedOut&&(l=!0);else{let h=m.reason instanceof Error?m.reason.message:String(m.reason);u[d]=`# ${t[d].label}
611
+
612
+ (executor error: ${h})
613
+ `}}return{outputs:u,timedOut:l}}function YP(t,e){let r=Vr();Tr(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:Kn()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
614
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function fi(t,e,r,n=5){let o=t.split(`
615
+ `).length,s=Buffer.byteLength(t),i=Vr(),a=i.indexPlainText(t,r,void 0,Kn()),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
616
+ `)}let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let m=d.content.split(`
617
+ `)[0].slice(0,120);l.push(` - ${d.title}: ${m}`)}return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),l.join(`
618
+ `)}function V_(t,e){let r=process.env[t];if(!r)return e;let n=Number(r);return Number.isFinite(n)&&n>0?n:e}function W_(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function K_(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function fZ(t){let e=W_(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function hZ(){return A_||(A_=AP(import.meta.url).resolve("turndown")),A_}function gZ(){return N_||(N_=AP(import.meta.url).resolve("turndown-plugin-gfm")),N_}function QP(t,e){let r=JSON.stringify(hZ()),n=JSON.stringify(gZ()),o=JSON.stringify(e),s=ec.toString(),i=ec.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
591
619
  var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
592
620
  const TurndownService = require(${r});
593
621
  const { gfm } = require(${n});
@@ -781,6 +809,25 @@ async function fetchWithManualRedirect(initialUrl) {
781
809
  throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
782
810
  }
783
811
 
812
+ // Subprocess response-body size cap. A malicious or unexpectedly large
813
+ // endpoint reachable through ctx_fetch_and_index would otherwise stream
814
+ // gigabytes into resp.text(), then into outputPath, then into the parent
815
+ // MCP server's heap via readFileSync. 50 MB is far above typical web
816
+ // page / API response sizes (~1-5 MB) but bounded enough to keep parent
817
+ // heap survivable. Cap both early via Content-Length and after the read.
818
+ const MAX_FETCH_BYTES = 50 * 1024 * 1024;
819
+ async function safeText(resp) {
820
+ const cl = parseInt(resp.headers.get('content-length') || '0', 10);
821
+ if (cl > MAX_FETCH_BYTES) {
822
+ throw new Error('Response too large: Content-Length ' + cl + ' exceeds ' + MAX_FETCH_BYTES);
823
+ }
824
+ const text = await resp.text();
825
+ if (text.length > MAX_FETCH_BYTES) {
826
+ throw new Error('Response too large: ' + text.length + ' bytes exceeds ' + MAX_FETCH_BYTES);
827
+ }
828
+ return text;
829
+ }
830
+
784
831
  async function main() {
785
832
  const resp = await fetchWithManualRedirect(url);
786
833
  if (!resp.ok) { console.error("HTTP " + resp.status); process.exit(1); }
@@ -788,7 +835,7 @@ async function main() {
788
835
 
789
836
  // --- JSON responses ---
790
837
  if (contentType.includes('application/json') || contentType.includes('+json')) {
791
- const text = await resp.text();
838
+ const text = await safeText(resp);
792
839
  try {
793
840
  const pretty = JSON.stringify(JSON.parse(text), null, 2);
794
841
  emit('json', pretty);
@@ -800,7 +847,7 @@ async function main() {
800
847
 
801
848
  // --- HTML responses (default for text/html, application/xhtml+xml) ---
802
849
  if (contentType.includes('text/html') || contentType.includes('application/xhtml')) {
803
- const html = await resp.text();
850
+ const html = await safeText(resp);
804
851
  const td = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' });
805
852
  td.use(gfm);
806
853
  td.remove(['script', 'style', 'nav', 'header', 'footer', 'noscript']);
@@ -809,18 +856,18 @@ async function main() {
809
856
  }
810
857
 
811
858
  // --- Everything else: plain text, CSV, XML, etc. ---
812
- const text = await resp.text();
859
+ const text = await safeText(resp);
813
860
  emit('text', text);
814
861
  }
815
862
  main();
816
- `}function GH(t){if(t===0)return"0ms";let e=1440*60*1e3,r=3600*1e3,n=60*1e3;return t%e===0?`${t/e}d`:t%r===0?`${t/r}h`:t%n===0?`${t/n}m`:`${t}ms`}async function KH(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),o=await n(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=Da(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){let o=n?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=n instanceof Error?n.message:String(n),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function Da(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?Da(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let o=r.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function JH(t,e,r,n){let o=await KH(t);if(o)return o;if(!r&&n!==0){let i=Un(),a=Jy(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),d=Date.now()-u.getTime(),l=n??WH;if(d<l){let m=Math.floor(d/36e5),f=Math.floor(d/(60*1e3)),p=m>0?`${m}h ago`:f>0?`${f}m ago`:"just now",h=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:h,ageStr:p,ttlStr:GH(l)}}}}let s=Oe(f_(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=sP(t,s),a=await ja.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let d=a.stderr||a.stdout||"unknown error",m=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(d)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${d}${m}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{u=Zl(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{zl(s)}catch{}}}function YH(t){let e=Un(),r=Jy(t.source,t.url),n=Ln(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,r,void 0,n):o=e.index({content:t.markdown,source:r,attribution:n}),wr(Buffer.byteLength(t.markdown));let s=t.markdown.length>FT?Q$(t.markdown,FT)+`
863
+ `}function _Z(t){if(t===0)return"0ms";let e=1440*60*1e3,r=3600*1e3,n=60*1e3;return t%e===0?`${t/e}d`:t%r===0?`${t/r}h`:t%n===0?`${t/n}m`:`${t}ms`}async function bZ(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),o=await n(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=ec(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){let o=n?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=n instanceof Error?n.message:String(n),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function ec(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?ec(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let o=r.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function xZ(t,e,r,n){let o=await bZ(t);if(o)return o;if(!r&&n!==0){let i=Vr(),a=w_(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=n??yZ;if(l<d){let m=Math.floor(l/36e5),h=Math.floor(l/(60*1e3)),p=m>0?`${m}h ago`:h>0?`${h}m ago`:"just now",f=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:f,ageStr:p,ttlStr:_Z(d)}}}}let s=Ce(U_(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=QP(t,s),a=await rc.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",m=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${m}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=rd(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=tc(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{td(s)}catch{}}}function vZ(t){let e=Vr(),r=w_(t.source,t.url),n=Kn(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,r,void 0,n):o=e.index({content:t.markdown,source:r,attribution:n}),Tr(Buffer.byteLength(t.markdown));let s=t.markdown.length>OP?FT(t.markdown,OP)+`
817
864
 
818
- \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function UT(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function iP(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function p_(t,e=process.platform,r=BT){let n=iP(t,e),o=[];for(let{cmd:s,args:i}of n)try{let a=r(s,i,{stdio:"ignore",timeout:Aa});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function v_(t,e=process.platform,r=BT){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let o=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Aa});if(o.error)return n.errors.push(`netstat: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let d=u[0],l=u[1],m=u[2],f=u[u.length-1];d==="TCP"&&l.endsWith(s)&&(m!=="0.0.0.0:0"&&m!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Aa});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Aa});if(o.error)return n.errors.push(`lsof: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:Aa});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){n.errors.push(o instanceof Error?o.message:String(o))}return n}async function XH(){let t=Gy();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?f_():"/tmp",r=Oe(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{ja.cleanupBackgrounded(),Sr&&Sr.close();try{Js(Bl)}catch{}try{Js(r)}catch{}if(rn&&rn.pid&&!rn.killed)try{rn.kill("SIGTERM")}catch{}},o=async()=>{try{d_=0,Fl()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),Y$({onShutdown:()=>o()});let s=new _l;await ze.connect(s);try{m_(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(yn(),bc)),c=ze.server.getClientVersion(),u=i(c??void 0);Fn=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=uT(Na());if(i){for(let[a,c]of Object.entries(i.calls))ie.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))ie.bytesReturned[a]=c;i.sessionStart>0&&(ie.sessionStart=i.sessionStart)}}catch{}NT().then(i=>{i!=="unknown"&&(on=i)}),setInterval(()=>{NT().then(i=>{i!=="unknown"&&(on=i)})},3600*1e3).unref(),setInterval(()=>Fl(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${nn} running on stdio`),console.error(`Detected runtimes:
819
- ${Ya(Ma)}`),Bn()||(console.error(`
820
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var Ft,nn,Ma,jl,ze,qT,WT,l_,_H,h_,ja,Bl,Sr,Nl,Fn,rn,ie,on,Dl,AT,$H,TH,DT,AH,NH,DH,MH,d_,Ml,jH,zH,LH,FH,Ul,Hl,Mo,i_,ZH,zT,LT,a_,c_,WH,FT,Aa,cP=S(()=>{"use strict";p$();g$();Fy();Zy();T$();Z$();B$();K$();Qa();J$();X$();eT();Tr();rT();iT();lT();gT();cn();yn();gd();hn();vT();ln();OT();Eo();Ft=kr(uH(import.meta.url)),nn=(()=>{for(let t of["../package.json","./package.json"]){let e=Ke(Ft,t);if($e(e))try{return JSON.parse(Zl(e,"utf8")).version}catch{}}return"unknown"})();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
865
+ \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function D_(t,e){if(!ke(e))return;let r=0;try{for(let n of NP(e))if(!(!n.startsWith("stats-")||!n.endsWith(".json")))try{let o=JSON.parse(tc(Ce(e,n),"utf-8"));r+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(r>0){let n=(t.rescueBytes??0)/4;t.totalEvents=Math.round((r/4+n)/256)}}function IP(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function eR(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function F_(t,e=process.platform,r=jP){let n=eR(t,e),o=[];for(let{cmd:s,args:i}of n)try{let a=r(s,i,{stdio:"ignore",timeout:Ya});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function G_(t,e=process.platform,r=jP){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let o=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Ya});if(o.error)return n.errors.push(`netstat: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],m=u[2],h=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(m!=="0.0.0.0:0"&&m!=="[::]:0"||/^\d+$/.test(h)&&i.add(h))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Ya});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Ya});if(o.error)return n.errors.push(`lsof: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:Ya});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){n.errors.push(o instanceof Error?o.message:String(o))}return n}async function SZ(){let t=Wp();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?U_():"/tmp",r=Ce(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{rc.cleanupBackgrounded(),Er&&Er.close();try{hi(ad)}catch{}try{hi(r)}catch{}if(pn&&pn.pid&&!pn.killed)try{pn.kill("SIGTERM")}catch{}},o=async()=>{try{L_=0,od()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),LT({onShutdown:()=>o()});let s=new Ll;await Fe.connect(s);try{H_(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>($n(),Lc)),c=Fe.server.getClientVersion(),u=i(c??void 0);$r=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=JT(Qa());if(i){for(let[a,c]of Object.entries(i.calls))ie.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))ie.bytesReturned[a]=c;i.sessionStart>0&&(ie.sessionStart=i.sessionStart)}}catch{}EP().then(i=>{i!=="unknown"&&(fn=i)}),setInterval(()=>{EP().then(i=>{i!=="unknown"&&(fn=i)})},3600*1e3).unref(),setInterval(()=>od(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${mn} running on stdio`),console.error(`Detected runtimes:
866
+ ${wi(Ko)}`),yn()||(console.error(`
867
+ Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var qt,mn,Ko,ed,Fe,LP,FP,j_,zB,B_,rc,ad,Er,Jl,$r,pn,ie,fn,Xl,wP,WB,KB,$P,eZ,tZ,rZ,nZ,L_,Yl,oZ,iZ,aZ,cZ,uZ,TP,PP,sd,id,qr,O_,mZ,I_,Ql,A_,N_,yZ,OP,Ya,rR=S(()=>{"use strict";xT();wT();Dl();S_();DT();Gp();MT();Qp();Xo();jT();zT();HT();Jt();BT();WT();XT();nP();iP();Cr();$n();Ld();kn();uP();bn();SP();jo();qt=Zt(CB(import.meta.url)),mn=(()=>{for(let t of["../package.json","./package.json"]){let e=Ve(qt,t);if(ke(e))try{return JSON.parse(tc(e,"utf8")).version}catch{}}return"unknown"})();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
821
868
  `)}),process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
822
- `)}));Ma=Lo(),jl=Xa(Ma),ze=new gl({name:"context-mode",version:nn}),qT=[];WT=VT(),l_=!1;_H=ze.registerTool.bind(ze);ze.registerTool=(...t)=>{let[e,r,n]=t;if(WT){GT();return}let o=vH(e,n);return qT.push({name:e,config:r,handler:o}),t[2]=o,_H(...t)};WT&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&KT(ze);h_=new pH;ze.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});ze.server.setRequestHandler(xs,async()=>({prompts:[]}));ze.server.setRequestHandler(vs,async()=>({resources:[]}));ze.server.setRequestHandler(bs,async()=>({resourceTemplates:[]}));ja=new Hs({runtimes:Ma,projectRoot:()=>Ut()}),Bl=Oe(f_(),`cm-fs-preload-${process.pid}.js`);m_(Bl,`(function(){var __cm_fs=0;process.on('exit',function(){if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch(e){}});try{var f=require('fs');var ors=f.readFileSync;f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};}catch(e){}})();
823
- `);process.on("exit",()=>{try{Js(Bl)}catch{}});Sr=null;Fn=null,rn=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()};on=null,Dl=0,AT=0,$H=3,TH=3600*1e3;DT=!1;AH=500,NH=2,DH=3e4,MH=256,d_=0;jH=jl.join(", "),zH=Bn()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",LH="",FH="";ze.registerTool("ctx_execute",{title:"Execute Code",description:`Run code in a sandboxed subprocess.${zH} Languages: ${jH}.
869
+ `)}));Ko=Yn(),ed=Ei(Ko),Fe=new Ml({name:"context-mode",version:mn}),LP=[];FP=zP(),j_=!1;zB=Fe.registerTool.bind(Fe);Fe.registerTool=(...t)=>{let[e,r,n]=t;if(FP){HP();return}let o=FB(e,n);return LP.push({name:e,config:r,handler:o}),t[2]=o,zB(...t)};FP&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&UP(Fe);B_=new AB;Fe.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Fe.server.setRequestHandler(Hs,async()=>({prompts:[]}));Fe.server.setRequestHandler(zs,async()=>({resources:[]}));Fe.server.setRequestHandler(Fs,async()=>({resourceTemplates:[]}));rc=new ci({runtimes:Ko,projectRoot:()=>Lt()}),ad=Ce(U_(),`cm-fs-preload-${process.pid}.js`);H_(ad,`(function(){var __cm_fs=0;process.on('exit',function(){if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch(e){}});try{var f=require('fs');var ors=f.readFileSync;f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};}catch(e){}})();
870
+ `);process.on("exit",()=>{try{hi(ad)}catch{}});Er=null;$r=null,pn=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};fn=null,Xl=0,wP=0,WB=3,KB=3600*1e3;$P=!1;eZ=500,tZ=2,rZ=3e4,nZ=256,L_=0,oZ=/^[A-Za-z0-9._-]+$/;iZ=ed.join(", "),aZ=yn()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",cZ="",uZ="";TP=500;PP=2e3;Fe.registerTool("ctx_execute",{title:"Execute Code",description:`Run code in a sandboxed subprocess.${aZ} Languages: ${iZ}.
824
871
 
825
872
  Think-in-Code \u2014 the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.
826
873
 
@@ -851,9 +898,9 @@ RETURNS:
851
898
  Only what your code prints. Wrap risky calls in try/catch \u2014 uncaught errors go to stderr and may leak more than intended. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.
852
899
 
853
900
  EXAMPLE: ctx_execute(language: "shell", code: "npm test 2>&1 | grep -E '(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))' | head -60")
854
- EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:D.object({language:D.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:D.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:D.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:D.preprocess(__,D.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:D.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
901
+ EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:M.object({language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:M.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:M.preprocess(K_,M.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:M.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
855
902
 
856
- TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=g_(e,"execute");if(s)return s}else{let s=XT(e,t,"execute");if(s)return s}try{let s=e;(t==="javascript"||t==="typescript")&&(s=`
903
+ TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=Z_(e,"execute");if(s)return s}else{let s=qP(e,t,"execute");if(s)return s}try{let s=e;(t==="javascript"||t==="typescript")&&(s=`
857
904
  // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
858
905
  let __cm_fs=0;
859
906
  process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
@@ -912,14 +959,14 @@ ${e}
912
959
  }
913
960
  __cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
914
961
  setInterval(()=>{},2147483647);`:""}
915
- })(typeof require!=='undefined'?require:null);`);let i=await ja.execute({language:t,code:s,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(ie.bytesSandboxed+=parseInt(a[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let c=i.stderr?.match(/__CM_FS__:(\d+)/);if(c&&(ie.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?G("ctx_execute",{content:[{type:"text",text:`${d}
962
+ })(typeof require!=='undefined'?require:null);`);let i=await rc.execute({language:t,code:s,timeout:r,background:n}),a=JP(t,e),c=i.stderr?.match(/__CM_NET__:(\d+)/);c&&(ie.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let u=i.stderr?.match(/__CM_FS__:(\d+)/);if(u&&(ie.bytesSandboxed+=parseInt(u[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?W("ctx_execute",{content:[{type:"text",text:`${a}${d}
916
963
 
917
- _(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?G("ctx_execute",{content:[{type:"text",text:`${d}
964
+ _(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?W("ctx_execute",{content:[{type:"text",text:`${a}${d}
918
965
 
919
- _(timed out after ${r}ms \u2014 partial output shown above)_`}]}):G("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
966
+ _(timed out after ${r}ms \u2014 partial output shown above)_`}]}):W("ctx_execute",{content:[{type:"text",text:`${a}Execution timed out after ${r}ms
920
967
 
921
968
  stderr:
922
- ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=e_({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(l)>Ul?(wr(Buffer.byteLength(l)),G("ctx_execute",{content:[{type:"text",text:Ks(l,o,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>Hl?(wr(Buffer.byteLength(l)),G("ctx_execute",{content:[{type:"text",text:Ks(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):G("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(u)>Ul?(wr(Buffer.byteLength(u)),G("ctx_execute",{content:[{type:"text",text:Ks(u,o,`execute:${t}`)}]})):Buffer.byteLength(u)>Hl?G("ctx_execute",oP(u,`execute:${t}`)):G("ctx_execute",{content:[{type:"text",text:u}]})}catch(s){let i=s instanceof Error?s.message:String(s);return G("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});Ul=5e3,Hl=102400;ze.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
969
+ ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:m}=E_({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(m)>sd?(Tr(Buffer.byteLength(m)),W("ctx_execute",{content:[{type:"text",text:`${a}${fi(m,o,d?`execute:${t}:error`:`execute:${t}`)}`}],isError:d})):Buffer.byteLength(m)>id?(Tr(Buffer.byteLength(m)),W("ctx_execute",{content:[{type:"text",text:`${a}${fi(m,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}`}],isError:d})):W("ctx_execute",{content:[{type:"text",text:`${a}${m}`}],isError:d})}let l=i.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>sd)return Tr(Buffer.byteLength(l)),W("ctx_execute",{content:[{type:"text",text:`${a}${fi(l,o,`execute:${t}`)}`}]});if(Buffer.byteLength(l)>id){let d=YP(l,`execute:${t}`),m={...d,content:d.content.map((h,p)=>p===0&&h.type==="text"?{...h,text:`${a}${h.text}`}:h)};return W("ctx_execute",m)}return W("ctx_execute",{content:[{type:"text",text:`${a}${l}`}]})}catch(s){let i=s instanceof Error?s.message:String(s);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});sd=5e3,id=102400;Fe.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
923
970
 
924
971
  Think-in-Code applied to file-level analysis: Reading the whole file means every byte enters your conversation memory and costs reasoning capacity for the rest of the session. Running code over it here lets you keep the raw bytes out and only the derived answer in. Same principle as ctx_execute, scoped to one named file via the FILE_CONTENT variable.
925
972
 
@@ -938,7 +985,7 @@ RETURNS:
938
985
  Only what your code prints. The FILE_CONTENT variable holds the raw bytes inside the sandbox; nothing else leaves. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout.
939
986
 
940
987
  EXAMPLE: ctx_execute_file(path: "huge.log", language: "javascript", code: "const errs = FILE_CONTENT.split('\\\\n').filter(l => /ERROR|FATAL/.test(l)); console.log(\`\${errs.length} error lines\`); console.log(errs.slice(-5).join('\\\\n'))")
941
- EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:D.object({path:D.string().describe("Absolute file path or relative to project root"),language:D.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:D.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:D.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:D.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=QT(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=g_(r,"execute_file");if(i)return i}else{let i=XT(r,e,"execute_file");if(i)return i}try{let i=await ja.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return G("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=e_({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(u)>Ul?(wr(Buffer.byteLength(u)),G("ctx_execute_file",{content:[{type:"text",text:Ks(u,o,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>Hl?(wr(Buffer.byteLength(u)),G("ctx_execute_file",{content:[{type:"text",text:Ks(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):G("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(a)>Ul?(wr(Buffer.byteLength(a)),G("ctx_execute_file",{content:[{type:"text",text:Ks(a,o,`file:${t}`)}]})):Buffer.byteLength(a)>Hl?G("ctx_execute_file",oP(a,`file:${t}`)):G("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return G("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});ze.registerTool("ctx_index",{title:"Index Content",description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
988
+ EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:M.object({path:M.string().describe("Absolute file path or relative to project root"),language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:M.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:M.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=z_(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=Z_(r,"execute_file");if(i)return i}else{let i=qP(r,e,"execute_file");if(i)return i}try{let i=await rc.executeFile({path:t,language:e,code:r,timeout:n}),a=JP(e,r,t);if(i.timedOut)return W("ctx_execute_file",{content:[{type:"text",text:`${a}Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:u,output:l}=E_({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(l)>sd?(Tr(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${a}${fi(l,o,u?`file:${t}:error`:`file:${t}`)}`}],isError:u})):Buffer.byteLength(l)>id?(Tr(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${a}${fi(l,"errors failures exceptions",u?`file:${t}:error`:`file:${t}`)}`}],isError:u})):W("ctx_execute_file",{content:[{type:"text",text:`${a}${l}`}],isError:u})}let c=i.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(c)>sd)return Tr(Buffer.byteLength(c)),W("ctx_execute_file",{content:[{type:"text",text:`${a}${fi(c,o,`file:${t}`)}`}]});if(Buffer.byteLength(c)>id){let u=YP(c,`file:${t}`),l={...u,content:u.content.map((d,m)=>m===0&&d.type==="text"?{...d,text:`${a}${d.text}`}:d)};return W("ctx_execute_file",l)}return W("ctx_execute_file",{content:[{type:"text",text:`${a}${c}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Fe.registerTool("ctx_index",{title:"Index Content",description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
942
989
 
943
990
  WHEN:
944
991
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
@@ -956,35 +1003,37 @@ RETURNS:
956
1003
  Indexing metadata: chunk counts (total, code-bearing), source label, and the exact ctx_search call shape to query the indexed content. Raw content is NOT echoed back \u2014 it lives in storage, retrievable via ctx_search(source: "<label>"). When \`path\` is provided, a content hash is stored so ctx_search results auto-flag staleness on future calls.
957
1004
 
958
1005
  EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
959
- EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:D.object({content:D.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:D.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:D.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:D.array(D.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:D.array(D.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:D.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:D.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:D.array(D.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:D.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:D.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:r,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return G("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let d=QT(e,"ctx_index");if(d)return d}try{let d=e?wH(e):void 0;if(d&&$e(d)&&u_(d).isDirectory()){let f=Un(),p=Ut(),h=Sl("Read",p),g=process.platform==="win32",y=P=>{try{return kl(P,h,g,p).denied}catch{return!1}},v=f.indexDirectory({path:d,source:r??d,attribution:Ln(),perFileDeny:y,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),_=v.capped?` (cap reached \u2014 only first ${v.filesIndexed} of ${v.totalSeen}+ files; raise maxFiles to index more)`:"",b=v.denied>0?` (${v.denied} file${v.denied===1?"":"s"} blocked by Read deny policy)`:"",x=v.failed>0?` (${v.failed} file${v.failed===1?"":"s"} failed to read)`:"";return G("ctx_index",{content:[{type:"text",text:`Indexed ${v.filesIndexed} file${v.filesIndexed===1?"":"s"} (${v.totalChunks} sections) from directory: ${v.label}${_}${b}${x}
960
- Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)wr(Buffer.byteLength(t));else if(d)try{let f=await import("fs");wr(f.readFileSync(d).byteLength)}catch{}let m=Un().index({content:t,path:d,source:r??d,attribution:Ln()});return G("ctx_index",{content:[{type:"text",text:`Indexed ${m.totalChunks} sections (${m.codeChunks} with code) from: ${m.label}
961
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${m.label}" to scope results.`}]})}catch(d){let l=d instanceof Error?d.message:String(d);return G("ctx_index",{content:[{type:"text",text:`Index error: ${l}`}],isError:!0})}});Mo=0,i_=Date.now(),ZH=6e4,zT=3,LT=8;ze.registerTool("ctx_search",{title:"Search Indexed Content",description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:D.object({queries:D.preprocess(ql,D.array(D.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:D.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:D.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:D.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:D.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory.")})},async t=>{try{let e=Un(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return G("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
1006
+ EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:M.object({content:M.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:M.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:M.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:M.array(M.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:M.array(M.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:M.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:M.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:M.array(M.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:M.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:M.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:r,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=z_(e,"ctx_index");if(l)return l}try{let l=e?qB(e):void 0;if(l&&ke(l)&&MP(l).isSymbolicLink()){let p;try{p=PB(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let f=z_(p,"ctx_index");if(f)return f}}if(l&&ke(l)&&rd(l).isDirectory()){let h=Vr(),p=Lt(),f=lo("Read",p),g=process.platform==="win32",y=C=>{try{return po(C,f,g,p).denied}catch{return!1}},_=h.indexDirectory({path:l,source:r??l,attribution:Kn(),perFileDeny:y,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),b=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",v=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",E=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return W("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${b}${v}${E}
1007
+ Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)Tr(Buffer.byteLength(t));else if(l)try{let h=await import("fs");Tr(h.readFileSync(l).byteLength)}catch{}let m=Vr().index({content:t,path:l,source:r??l,attribution:Kn()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${m.totalChunks} sections (${m.codeChunks} with code) from: ${m.label}
1008
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${m.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return W("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});qr=0,O_=Date.now(),mZ=V_("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),I_=V_("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),Ql=V_("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8);Fe.registerTool("ctx_search",{title:"Search Indexed Content",description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:oP(C_)},async t=>{try{let e=Vr(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return W("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
962
1009
 
963
1010
  ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
964
1011
  \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
965
1012
  \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
966
1013
  \u2022 ctx_index(content, source) \u2014 manually index text content
967
1014
 
968
- After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return G("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a}=t,c=Date.now();if(c-i_>ZH&&(Mo=0,i_=c),Mo++,Mo>LT)return G("ctx_search",{content:[{type:"text",text:`BLOCKED: ${Mo} search calls in ${Math.round((c-i_)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let u=Mo>zT?1:Math.min(s,2),d=40*1024,l=0,m=[],f=null;if(r==="timeline")try{let g=Xe(),y=Ut(),v=pi({projectDir:y,sessionsDir:g});$e(v)&&(f=new ur({dbPath:v}))}catch{}let p=Fn?.getConfigDir()??qe();try{for(let g of o){if(l>d){m.push(`## ${g}
1015
+ After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return W("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=sP(c,C_,()=>Lt()),l=Date.now();if(l-O_>mZ&&(qr=0,O_=l),qr++,qr>Ql)return W("ctx_search",{content:[{type:"text",text:`BLOCKED: ${qr} search calls in ${Math.round((l-O_)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let d=qr>I_?1:Math.min(s,2),m=40*1024,h=0,p=[],f=null;if(r==="timeline"||typeof u=="string")try{let C=Be(),x=Lt(),k=cs({projectDir:x,sessionsDir:C});ke(k)&&(f=new Gt({dbPath:k}))}catch{}let y;if(typeof u=="string"&&f)try{y=new Set(f.getSessionIdsForProject(u))}catch{}let _=$r?.getConfigDir()??qe();try{for(let C of o){if(h>m){p.push(`## ${C}
969
1016
  (output cap reached)
970
- `);continue}let y;if(r==="timeline"?y=hT({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:Ut(),configDir:p,adapter:Fn??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){m.push(`## ${g}
971
- No results found.`);continue}let v=y.map((_,b)=>{let x=_.origin||"current-session",P=_.timestamp?_.timestamp.slice(0,16).replace("T"," "):"",E=`--- [${x}${P?" | "+P:""} | ${_.source}] ---`,R=`### ${_.title}`,A=y_(_.content,g,1500,_.highlighted);return`${E}
972
- ${R}
1017
+ `);continue}let x;if(r==="timeline"?x=rP({query:C,limit:d,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:Lt(),configDir:_,adapter:$r??void 0,projectScope:u}):x=e.searchWithFallback(C,d,i,a,"like",y),x.length===0){p.push(`## ${C}
1018
+ No results found.`);continue}let k=x.map((P,N)=>{let R=P.origin||"current-session",O=P.timestamp?P.timestamp.slice(0,16).replace("T"," "):"",F=`--- [${R}${O?" | "+O:""} | ${P.source}] ---`,K=`### ${P.title}`,ge=q_(P.content,C,1500,P.highlighted);return`${F}
1019
+ ${K}
973
1020
 
974
- ${A}`}).join(`
1021
+ ${ge}`}).join(`
975
1022
 
976
- `);m.push(`## ${g}
1023
+ `);p.push(`## ${C}
977
1024
 
978
- ${v}`),l+=v.length}}finally{try{f?.close()}catch{}}let h=m.join(`
1025
+ ${k}`),h+=k.length}}finally{try{f?.close()}catch{}}let b=p.join(`
979
1026
 
980
1027
  ---
981
1028
 
982
- `);if(e.lastRefreshCount>0&&(h=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
1029
+ `);e.lastRefreshCount>0&&(b=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
1030
+
1031
+ `+b);let v=Math.max(0,Ql-qr),E=Math.max(0,I_-qr);if(qr>=I_?b+=`
983
1032
 
984
- `+h),Mo>=zT&&(h+=`
1033
+ \u26A0 search call #${qr}/${Ql} in this window. Results limited to ${d}/query. ${v} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:b+=`
985
1034
 
986
- \u26A0 search call #${Mo}/${LT} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),y=g.length>0?`
987
- Indexed sources: ${g.map(v=>`"${v.label}" (${v.chunkCount} sections)`).join(", ")}`:"";return G("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return G("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return G("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});a_=null,c_=null;WH=1440*60*1e3,FT=3072;ze.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
1035
+ > Throttle: call #${qr}/${Ql} in this window. ${E} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,b.trim().length===0){let C=e.listSources(),x=C.length>0?`
1036
+ Indexed sources: ${C.map(k=>`"${k.label}" (${k.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${x}`}]})}return W("ctx_search",{content:[{type:"text",text:b}]})}catch(e){let r=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});A_=null,N_=null;yZ=1440*60*1e3,OP=3072;Fe.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
988
1037
 
989
1038
  Caching: every fetch is cached on disk and reused for repeat calls within the TTL window. The default TTL is 24 hours; override per-call with the \`ttl\` parameter (milliseconds, \`ttl: 0\` bypasses cache like \`force: true\`). Stored content older than 14 days is cleaned up on startup.
990
1039
 
@@ -1004,15 +1053,15 @@ RETURNS:
1004
1053
  EXAMPLE: ctx_fetch_and_index(
1005
1054
  requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
1006
1055
  concurrency: 5
1007
- )`,inputSchema:D.object({url:D.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:D.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:D.preprocess(ql,D.array(D.object({url:D.string().describe("URL to fetch"),source:D.string().optional().describe("Label for this URL's indexed content")})).min(1)).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:D.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:D.preprocess(__,D.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:D.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:r,concurrency:n,force:o,ttl:s})=>{let i=r||(t?[{url:t,source:e}]:[]);if(i.length===0)return G("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!r&&i.length===1,c=n??1,u=i.map(w=>({run:()=>JH(w.url,w.source,o,s)})),{settled:d,effectiveConcurrency:l,capped:m}=await By(u,{concurrency:c,capByCpuCount:!a&&c>1}),f=[];for(let w=0;w<d.length;w++){let F=d[w];if(F.status==="rejected"){let te=F.reason instanceof Error?F.reason.message:String(F.reason);f.push({kind:"job_error",url:i[w].url,error:te});continue}let U=F.value;if(U.kind==="cached"){ie.cacheHits++,ie.cacheBytesSaved+=U.estimatedBytes;let te=U.estimatedBytes,Ze=U.label;setImmediate(()=>sT({sessionDbPath:Na(),source:Ze,bytesAvoided:te})),f.push({kind:"cached",label:U.label,chunkCount:U.chunkCount,ageStr:U.ageStr,ttlStr:U.ttlStr})}else U.kind==="fetch_error"?f.push({kind:"fetch_error",url:U.url,error:U.error,reason:U.reason}):f.push({kind:"fetched",indexed:YH(U)})}if(a){let w=f[0];if(w.kind==="cached")return G("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${w.label}** \u2014 ${w.chunkCount} sections, indexed ${w.ageStr} (fresh, TTL: ${w.ttlStr}).
1056
+ )`,inputSchema:M.object({url:M.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:M.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:M.preprocess(W_,M.array(M.object({url:M.string().describe("URL to fetch"),source:M.string().optional().describe("Label for this URL's indexed content")})).min(1)).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:M.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:M.preprocess(K_,M.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:M.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:r,concurrency:n,force:o,ttl:s})=>{let i=r||(t?[{url:t,source:e}]:[]);if(i.length===0)return W("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!r&&i.length===1,c=n??1,u=i.map(R=>({run:()=>xZ(R.url,R.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:m}=await k_(u,{concurrency:c,capByCpuCount:!a&&c>1}),h=[];for(let R=0;R<l.length;R++){let O=l[R];if(O.status==="rejected"){let K=O.reason instanceof Error?O.reason.message:String(O.reason);h.push({kind:"job_error",url:i[R].url,error:K});continue}let F=O.value;if(F.kind==="cached"){ie.cacheHits++,ie.cacheBytesSaved+=F.estimatedBytes;let K=F.estimatedBytes,ge=F.label;setImmediate(()=>VT({sessionDbPath:Qa(),source:ge,bytesAvoided:K})),h.push({kind:"cached",label:F.label,chunkCount:F.chunkCount,ageStr:F.ageStr,ttlStr:F.ttlStr})}else F.kind==="fetch_error"?h.push({kind:"fetch_error",url:F.url,error:F.error,reason:F.reason}):(ie.cacheMisses++,h.push({kind:"fetched",indexed:vZ(F)}))}if(a){let R=h[0];if(R.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${R.label}** \u2014 ${R.chunkCount} sections, indexed ${R.ageStr} (fresh, TTL: ${R.ttlStr}).
1008
1057
  To refresh: call ctx_fetch_and_index again with \`force: true\`.
1009
1058
 
1010
1059
  You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
1011
- Use: ctx_search(queries: [...], source: "${w.label}")`}]});if(w.kind==="fetched"){let F=(w.indexed.totalBytes/1024).toFixed(1),U=[`Fetched and indexed **${w.indexed.totalChunks} sections** (${F}KB) from: ${w.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${w.indexed.label}") for specific lookups.`,"","---","",w.indexed.preview].join(`
1012
- `);return G("ctx_fetch_and_index",{content:[{type:"text",text:U}]})}if(w.kind==="fetch_error"){let F=w.reason==="empty"?`Fetched ${w.url} but got empty content`:w.reason==="read"?`Fetched ${w.url} but could not read subprocess output`:w.reason==="exit"?`Failed to fetch ${w.url}: ${w.error}`:`Fetch error: ${w.error}`;return G("ctx_fetch_and_index",{content:[{type:"text",text:F}],isError:!0})}return G("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${w.error}`}],isError:!0})}let p=384,h=[],g=0,y=0,v=0,_=0,b=0,x=[];for(let w of f)if(w.kind==="cached")v++,h.push(`- [cache] ${w.label} \u2014 ${w.chunkCount} sections (${w.ageStr}, TTL: ${w.ttlStr})`);else if(w.kind==="fetched"){_++,g+=w.indexed.totalChunks,y+=w.indexed.totalBytes;let F=(w.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${w.indexed.label} \u2014 ${w.indexed.totalChunks} sections (${F}KB)`);let U=w.indexed.preview.length>p?w.indexed.preview.slice(0,p).trimEnd()+"\u2026":w.indexed.preview;x.push(`### ${w.indexed.label}
1060
+ Use: ctx_search(queries: [...], source: "${R.label}")`}]});if(R.kind==="fetched"){let O=(R.indexed.totalBytes/1024).toFixed(1),F=[`Fetched and indexed **${R.indexed.totalChunks} sections** (${O}KB) from: ${R.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${R.indexed.label}") for specific lookups.`,"","---","",R.indexed.preview].join(`
1061
+ `);return W("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if(R.kind==="fetch_error"){let O=R.reason==="empty"?`Fetched ${R.url} but got empty content`:R.reason==="read"?`Fetched ${R.url} but could not read subprocess output`:R.reason==="exit"?`Failed to fetch ${R.url}: ${R.error}`:`Fetch error: ${R.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:O}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${R.error}`}],isError:!0})}let p=384,f=[],g=0,y=0,_=0,b=0,v=0,E=[];for(let R of h)if(R.kind==="cached")_++,f.push(`- [cache] ${R.label} \u2014 ${R.chunkCount} sections (${R.ageStr}, TTL: ${R.ttlStr})`);else if(R.kind==="fetched"){b++,g+=R.indexed.totalChunks,y+=R.indexed.totalBytes;let O=(R.indexed.totalBytes/1024).toFixed(1);f.push(`- [new] ${R.indexed.label} \u2014 ${R.indexed.totalChunks} sections (${O}KB)`);let F=R.indexed.preview.length>p?R.indexed.preview.slice(0,p).trimEnd()+"\u2026":R.indexed.preview;E.push(`### ${R.indexed.label}
1013
1062
 
1014
- ${U}`)}else b++,h.push(`- [err] ${w.url}: ${w.error}`);let P=(y/1024).toFixed(1),E=m?` cap=${l}/${lH().length}cpu`:"",R=(w,F,U)=>`${w} ${w===1?F:U}`,L=[`fetched ${i.length} c=${l}${E}. ok=${_} cache=${v} err=${b}. ${R(g,"section","sections")} ${P}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...x.length>0?["","---","",...x]:[]].join(`
1015
- `);return G("ctx_fetch_and_index",{content:[{type:"text",text:L}],isError:b===i.length})});ze.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
1063
+ ${F}`)}else v++,f.push(`- [err] ${R.url}: ${R.error}`);let C=(y/1024).toFixed(1),x=m?` cap=${d}/${OB().length}cpu`:"",k=(R,O,F)=>`${R} ${R===1?O:F}`,N=[`fetched ${i.length} c=${d}${x}. ok=${b} cache=${_} err=${v}. ${k(g,"section","sections")} ${C}KB.`,"",...f,"",'ctx_search(queries: [...], source: "<label>") for full content.',...E.length>0?["","---","",...E]:[]].join(`
1064
+ `);return W("ctx_fetch_and_index",{content:[{type:"text",text:N}],isError:v===i.length})});Fe.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
1016
1065
 
1017
1066
  Concurrency parallelizes the FETCH phase (run-the-commands). The DERIVATION phase \u2014 turning raw output into an answer \u2014 still belongs in code: add a processing command that consumes the indexed output and prints only the answer, so the raw bytes never enter your conversation (Think-in-Code, same principle as the sandbox tool).
1018
1067
 
@@ -1037,14 +1086,14 @@ EXAMPLE: ctx_batch_execute(
1037
1086
  ],
1038
1087
  queries: ["root cause", "proposed fix"],
1039
1088
  concurrency: 2
1040
- )`,inputSchema:D.object({commands:D.preprocess(BH,D.array(D.object({label:D.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:D.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:D.preprocess(ql,D.array(D.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:D.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:D.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let o of t){let s=g_(o.command,"batch_execute");if(s)return s}try{let o=rP(Ma.shell,Bl),{outputs:s,timedOut:i}=await nP(t,{timeout:r,concurrency:n,nodeOptsPrefix:o,onFsBytes:_=>{ie.bytesSandboxed+=_}},ja),a=s.join(`
1041
- `),c=Buffer.byteLength(a),u=a.split(`
1042
- `).length;if(i&&s.length===0)return G("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});wr(c);let d=Un(),l=`batch:${t.map(_=>_.label).join(",").slice(0,80)}`,m=d.index({content:a,source:l,attribution:Ln()}),f=d.getChunksBySource(m.sourceId),p=["## Indexed Sections",""],h=[];for(let _ of f){let b=Buffer.byteLength(_.content);p.push(`- ${_.title} (${(b/1024).toFixed(1)}KB)`),h.push(_.title)}let g=tP(d,e,l),y=d.getDistinctiveTerms?d.getDistinctiveTerms(m.sourceId):[],v=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${m.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,y.length>0?`
1043
- Searchable terms for follow-up: ${y.join(", ")}`:""].join(`
1044
- `);return G("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(o){let s=o instanceof Error?o.message:String(o);return G("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${s}`}],isError:!0})}});ze.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:D.object({})},async()=>{let t;try{let e=Ut(),r=gt(e),n=pi({projectDir:e,sessionsDir:Xe()});if($e(n)){let o=Qe(),s=new o(n,{readonly:!0});try{let i=new Ws(s),a=i.queryAll(ie),c=i.getMcpToolUsage(),u=Oa({sessionsDir:Xe()}),d;try{d=Ol()}catch{}let l,m;try{let f=process.env.CLAUDE_SESSION_ID;if(f||(f=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),f){l=PT({sessionId:f,sessionsDir:Xe(),worktreeHash:r});let p=Ll(),h;try{let _=Qe(),b=(await import("node:fs")).readdirSync(Xe()).filter(P=>P.endsWith(".db")&&(!r||P.startsWith(r))),x;for(let P of b)try{let E=new _((await import("node:path")).join(Xe(),P),{readonly:!0});try{let R=E.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(f);if(R?.project_dir){x=R.project_dir;break}}finally{E.close()}}catch{}h=x?Ia({projectDir:x,sessionsDir:Xe(),worktreeHash:r,contentDbPath:p}):Ia({sessionId:f,sessionsDir:Xe(),worktreeHash:r,contentDbPath:p})}catch{h=Ia({sessionId:f,sessionsDir:Xe(),worktreeHash:r,contentDbPath:p})}let g=Ia({sessionsDir:Xe()}),y=RT(p),v={...g,contentBytes:g.contentBytes+y,bytesAvoided:g.bytesAvoided+y,totalSavedTokens:Math.floor((g.eventDataBytes+g.bytesAvoided+y+g.snapshotBytes)/4)};m={conversation:h,lifetime:v}}}catch{}t=Al(a,nn,on,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:m,cwd:e})}finally{s.close()}}else{let s=new Ws(UT()).queryAll(ie),i=Oa({sessionsDir:Xe()}),a;try{a=Ol()}catch{}t=Al(s,nn,on,{lifetime:i,multiAdapter:a})}}catch{let r=new Ws(UT()).queryAll(ie),n;try{n=Oa({sessionsDir:Xe()})}catch{}let o;try{o=Ol()}catch{}t=Al(r,nn,on,n||o?{lifetime:n,multiAdapter:o}:void 0)}return G("ctx_stats",{content:[{type:"text",text:t}]})});ze.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:D.object({})},async()=>{let t=["context-mode doctor",""],e=$e(Ke(Ft,"package.json"))?Ft:kr(Ft),r=11,n=(jl.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${jl.length}/${r} (${n}%) \u2014 ${jl.join(", ")}`),Bn()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let o=pn(Gs),s=qo(Gs),i=ui(Gs);t.push(`[OK] Storage sessions: ${o.path} (${cc(o)})`),t.push(`[OK] Storage content: ${s.path} (${cc(s)})`),t.push(`[OK] Storage stats: ${i.path} (${cc(i)})`);{let c=new Hs({runtimes:Ma});try{let u=await c.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(u.exitCode===0&&u.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=u.stderr?.trim()?` (${u.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${u.exitCode}${d}`)}}catch(u){t.push(`[FAIL] Server test: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{c.cleanupBackgrounded()}}{let c;try{let u=Qe();c=new u(":memory:"),c.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),c.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=c.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();d&&d.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(u){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{try{c?.close()}catch{}}}let a=await SH();if(a){for(let u of a.validateHooks(e)){let d=u.status==="pass"?"[OK]":u.status==="warn"?"[WARN]":"[FAIL]",l=u.fix?` \u2014 fix: ${u.fix}`:"";t.push(`${d} ${u.check}: ${u.message}${l}`)}let c=tc(a,e);c.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let u of c){let d=Ke(e,u);$e(d)?t.push(`[OK] Hook script: PASS \u2014 ${d}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${d}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${nn}`),G("ctx_doctor",{content:[{type:"text",text:t.join(`
1045
- `)}]})});ze.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:D.object({})},async()=>{let t=$e(Ke(Ft,"package.json"))?Ft:kr(Ft),e=Ke(t,"cli.bundle.mjs"),r=Ke(t,"build","cli.js");try{let i=Xe(),a=Oe(kr(i),"insight-cache");$e(a)&&(v_(4747),zl(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(yn(),bc)),a=ze.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let o;if($e(e))o=`${Fe(e)} upgrade${n}`;else if($e(r))o=`${Fe(r)} upgrade${n}`;else{let a=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync}from"node:fs";','import{join}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"for(const item of items){const from=join(T,item);const to=join(P,item);if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
1046
- `),c=Ke(t,".ctx-upgrade-inline.mjs"),{writeFileSync:u}=await import("node:fs");u(c,a),o=Fe(c)}let s=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",o,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
1047
- `);return G("ctx_upgrade",{content:[{type:"text",text:s}]})});ze.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
1089
+ )`,inputSchema:M.object({commands:M.preprocess(fZ,M.array(M.object({label:M.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:M.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:M.preprocess(W_,M.array(M.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:M.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip."),query_scope:M.enum(["batch","global"]).optional().default("batch").describe("Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands \u2014 useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) \u2014 useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.")})},async({commands:t,queries:e,timeout:r,concurrency:n,query_scope:o})=>{for(let s of t){let i=Z_(s.command,"batch_execute");if(i)return i}try{let s=KP(Ko.shell,ad),{outputs:i,timedOut:a}=await XP(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:E=>{ie.bytesSandboxed+=E}},rc),c=i.join(`
1090
+ `),u=Buffer.byteLength(c),l=c.split(`
1091
+ `).length;if(a&&i.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});Tr(u);let d=Vr(),m=`batch:${t.map(E=>E.label).join(",").slice(0,80)}`,h=d.index({content:c,source:m,attribution:Kn()}),p=["## Commands",""];for(let E of t)p.push(`- ${E.label}: \`${GP(E.command)}\``);let f=d.getChunksBySource(h.sourceId),g=["## Indexed Sections",""],y=[];for(let E of f){let C=Buffer.byteLength(E.content);g.push(`- ${E.title} (${(C/1024).toFixed(1)}KB)`),y.push(E.title)}let _=WP(d,e,m,void 0,o),b=d.getDistinctiveTerms?d.getDistinctiveTerms(h.sourceId):[],v=[`Executed ${t.length} commands (${l} lines, ${(u/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,"",..._,b.length>0?`
1092
+ Searchable terms for follow-up: ${b.join(", ")}`:""].join(`
1093
+ `);return W("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(s){let i=s instanceof Error?s.message:String(s);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${i}`}],isError:!0})}});Fe.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:M.object({})},async()=>{let t;try{let e=Lt(),r=nt(e),n=cs({projectDir:e,sessionsDir:Be()});if(ke(n)){let o=rt(),s=new o(n,{readonly:!0});try{let i=new pi(s),a=i.queryAll(ie),c=i.getMcpToolUsage(),u=Ga({sessionsDir:Be()}),l;try{l=Kl()}catch{}let d,m;try{let p=process.env.CLAUDE_SESSION_ID;if(p||(p=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),p){d=bP({sessionId:p,sessionsDir:Be(),worktreeHash:r});let f=nd(),g;try{let v=rt(),E=(await import("node:fs")).readdirSync(Be()).filter(x=>x.endsWith(".db")&&(!r||x.startsWith(r))),C;for(let x of E)try{let k=new v((await import("node:path")).join(Be(),x),{readonly:!0});try{let P=k.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(P?.project_dir){C=P.project_dir;break}}finally{k.close()}}catch{}g=C?Ja({projectDir:C,sessionsDir:Be(),worktreeHash:r,contentDbPath:f}):Ja({sessionId:p,sessionsDir:Be(),worktreeHash:r,contentDbPath:f})}catch{g=Ja({sessionId:p,sessionsDir:Be(),worktreeHash:r,contentDbPath:f})}let y=Ja({sessionsDir:Be()}),_=xP(f),b={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};m={conversation:g,lifetime:b}}}catch{}$r?.name==="Pi"&&D_(u,Be());let h;try{h=Vr().getIndexState()}catch{}t=Gl(a,mn,fn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:m,indexState:h,cwd:e})}finally{s.close()}}else{let s=new pi(IP()).queryAll(ie),i=Ga({sessionsDir:Be()});$r?.name==="Pi"&&D_(i,Be());let a;try{a=Kl()}catch{}let c;try{c=Vr().getIndexState()}catch{}t=Gl(s,mn,fn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let r=new pi(IP()).queryAll(ie),n;try{n=Ga({sessionsDir:Be()})}catch{}$r?.name==="Pi"&&n&&D_(n,Be());let o;try{o=Kl()}catch{}t=Gl(r,mn,fn,n||o?{lifetime:n,multiAdapter:o}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Fe.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:M.object({})},async()=>{let t=["context-mode doctor",""],e=ke(Ve(qt,"package.json"))?qt:Zt(qt),r=11,n=(ed.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${ed.length}/${r} (${n}%) \u2014 ${ed.join(", ")}`),yn()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let o=Jr(mi),s=vn(mi),i=ss(mi);t.push(`[OK] Storage sessions: ${o.path} (${Ri(o)})`),t.push(`[OK] Storage content: ${s.path} (${Ri(s)})`),t.push(`[OK] Storage stats: ${i.path} (${Ri(i)})`);{let c=new ci({runtimes:Ko});try{let u=await c.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(u.exitCode===0&&u.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let l=u.stderr?.trim()?` (${u.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${u.exitCode}${l}`)}}catch(u){t.push(`[FAIL] Server test: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{c.cleanupBackgrounded()}}{let c;try{let u=rt();c=new u(":memory:"),c.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),c.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let l=c.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();l&&l.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(u){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{try{c?.close()}catch{}}}let a=await BB();if(a){for(let u of a.validateHooks(e)){let l=u.status==="pass"?"[OK]":u.status==="warn"?"[WARN]":"[FAIL]",d=u.fix?` \u2014 fix: ${u.fix}`:"";t.push(`${l} ${u.check}: ${u.message}${d}`)}let c=_c(a,e);c.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let u of c){let l=Ve(e,u);ke(l)?t.push(`[OK] Hook script: PASS \u2014 ${l}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${l}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${mn}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
1094
+ `)}]})});Fe.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:M.object({})},async()=>{let t=ke(Ve(qt,"package.json"))?qt:Zt(qt),e=Ve(t,"cli.bundle.mjs"),r=Ve(t,"build","cli.js");try{let a=Be(),c=Ce(Zt(a),"insight-cache");ke(c)&&(G_(4747),td(c,{recursive:!0,force:!0}))}catch{}let n="",o;try{let{detectPlatform:a}=await Promise.resolve().then(()=>($n(),Lc)),c=Fe.server.getClientVersion(),u=a(c??void 0);n=` --platform ${u.platform}`,o=Xn(u.platform)&&Ko.javascript?{platform:u.platform,jsRuntime:Ko.javascript}:void 0}catch{}let s;if(ke(e))s=`${Si(e,o)} upgrade${n}`;else if(ke(r))s=`${Si(r,o)} upgrade${n}`;else{let c=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync,lstatSync}from"node:fs";','import{join,resolve,sep}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"const PW=resolve(P)+sep;const TW=resolve(T)+sep;","const noSymlink=(src)=>{try{return !lstatSync(src).isSymbolicLink()}catch{return false}};","for(const item of items){const from=resolve(T,item);const to=resolve(P,item);if(!(to+sep).startsWith(PW))continue;if(!(from+sep).startsWith(TW))continue;if(!noSymlink(from))continue;if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true,filter:noSymlink});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
1095
+ `),u=Ve(t,".ctx-upgrade-inline.mjs"),{writeFileSync:l}=await import("node:fs");l(u,c),s=Si(u,o)}let i=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",s,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
1096
+ `);return W("ctx_upgrade",{content:[{type:"text",text:i}]})});Fe.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
1048
1097
 
1049
1098
  WHEN:
1050
1099
  - User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
@@ -1068,83 +1117,85 @@ RETURNS:
1068
1117
  A summary of removed rows + the resolved scope.
1069
1118
 
1070
1119
  EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
1071
- EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:D.object({confirm:D.preprocess(__,D.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:D.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:D.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return G("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return G("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=Ll()}catch{}if(Sr){try{Sr.cleanup()}catch{}Sr=null}let s=o?kr(o):void 0,{deleted:i}=tT({projectDir:Ut(),sessionsDir:Xe(),storePath:o,contentDir:s,legacyContentDir:Oe(Ys(),".context-mode","content"),contentHash:Ur(Ut()),scope:n,sessionId:e});if(n==="project"){ie.calls={},ie.bytesReturned={},ie.bytesIndexed=0,ie.bytesSandboxed=0,ie.cacheHits=0,ie.cacheBytesSaved=0,ie.sessionStart=Date.now(),i.push("session stats");try{let c=YT();$e(c)&&Js(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return G("ctx_purge",{content:[{type:"text",text:a}]})});Aa=5e3;ze.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly. Defaults to port 4747; pass `port` to override. `sessionDir` and `contentDir` override the session/content storage roots (env aliases INSIGHT_SESSION_DIR / INSIGHT_CONTENT_DIR) for diagnosing multi-install setups or pointing at a sibling project's data.",inputSchema:D.object({port:D.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:D.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:D.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:D.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:D.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:o})=>{let s=t||4747,i=e||n,a=r||o,c=$e(Ke(Ft,"package.json"))?Ft:kr(Ft),u=Ke(c,"insight"),d=i?Ke(i):Xe(),l=a?Ke(a):Oe(kr(d),"content"),m=Oe(kr(d),"insight-cache");if(!$e(Oe(u,"server.mjs")))return G("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],p=!1;ZT(m,{recursive:!0});let h=u_(Oe(u,"server.mjs")).mtimeMs,g=$e(Oe(m,"server.mjs"))?u_(Oe(m,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),oH(u,m,{recursive:!0,force:!0}),f.push("Source files copied."),p=!0),!$e(Oe(m,"node_modules"))||p){f.push("Installing dependencies (first run, ~30s)...");try{IT(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{zl(Oe(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!$e(Oe(m,"node_modules","vite"))||!$e(Oe(m,"node_modules","better-sqlite3")))throw zl(Oe(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),IT("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let v=!1;try{let{request:R}=await import("node:http");await new Promise((A,L)=>{let w=R(`http://127.0.0.1:${s}/api/overview`,{timeout:2e3},F=>{F.resume(),A()});w.on("error",()=>L()),w.on("timeout",()=>{w.destroy(),L()}),w.end()}),v=!0}catch{}if(v&&p){f.push("Killing stale dashboard server (source updated)...");let R=v_(s);if(R.attemptedPids.length>0&&R.killedPids.length===0)return G("ctx_insight",{content:[{type:"text",text:`Could not free port ${s} (kill failed for ${R.attemptedPids.join(", ")}: ${R.errors.join("; ")}). Try ctx_insight({ port: ${s+1} }) or stop the process manually.`}]});if(R.errors.length>0&&R.attemptedPids.length===0)return G("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${s}: ${R.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(A=>setTimeout(A,500)),f.push(`Stale server killed (${R.killedPids.length} pid${R.killedPids.length===1?"":"s"}).`)}else if(v){f.push("Dashboard already running.");let R=`http://localhost:${s}`,A=p_(R),L=A.ok?"":` (auto-open failed: ${A.reason}; navigate manually)`;return G("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${R}${L}`}]})}if(rn&&rn.pid&&!rn.killed)try{rn.kill("SIGTERM")}catch{}let{spawn:_}=await import("node:child_process"),b=_("node",[Oe(m,"server.mjs")],{cwd:m,env:{...process.env,PORT:String(s),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});b.on("error",()=>{}),b.unref(),rn=b,await new Promise(R=>setTimeout(R,1500));try{let{request:R}=await import("node:http");await new Promise((A,L)=>{let w=R(`http://127.0.0.1:${s}/api/overview`,{timeout:3e3},F=>{A(),F.resume()});w.on("error",L),w.on("timeout",()=>{w.destroy(),L(new Error("timeout"))}),w.end()})}catch{return G("ctx_insight",{content:[{type:"text",text:`Port ${s} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
1120
+ EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:M.object({confirm:M.preprocess(K_,M.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:M.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:M.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return W("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=nd()}catch{}if(Er){try{Er.cleanup()}catch{}Er=null}let s=o?Zt(o):void 0,{deleted:i}=UT({projectDir:Lt(),sessionsDir:Be(),storePath:o,contentDir:s,legacyContentDir:Ce(gi(),".context-mode","content"),contentHash:Ar(Lt()),scope:n,sessionId:e});if(n==="project"){ie.calls={},ie.bytesReturned={},ie.bytesIndexed=0,ie.bytesSandboxed=0,ie.cacheHits=0,ie.cacheBytesSaved=0,ie.sessionStart=Date.now(),i.push("session stats");try{let c=ZP();ke(c)&&hi(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return W("ctx_purge",{content:[{type:"text",text:a}]})});Ya=5e3;Fe.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser \u2014 a dashboard launcher for session analytics; for natural-language queries over indexed content, use ctx_search. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly. Defaults to port 4747; pass `port` to override. `sessionDir` and `contentDir` override the session/content storage roots (env aliases INSIGHT_SESSION_DIR / INSIGHT_CONTENT_DIR) for diagnosing multi-install setups or pointing at a sibling project's data.",inputSchema:M.object({port:M.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:M.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:M.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:M.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:M.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:o})=>{let s=t||4747,i=e||n,a=r||o,c=ke(Ve(qt,"package.json"))?qt:Zt(qt),u=Ve(c,"insight"),l=i?Ve(i):Be(),d=a?Ve(a):Ce(Zt(l),"content"),m=Ce(Zt(l),"insight-cache");if(i||a){let h=Be(),p=Zt(Zt(h)),f=Ve(p)+M_,g=y=>(Ve(y)+M_).startsWith(f);if(i&&!g(l))return W("ctx_insight",{content:[{type:"text",text:`Error: sessionDir must resolve under ${p} (got ${l}).`}]});if(a&&!g(d))return W("ctx_insight",{content:[{type:"text",text:`Error: contentDir must resolve under ${p} (got ${d}).`}]})}if(!ke(Ce(u,"server.mjs")))return W("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let h=[],p=!1;DP(m,{recursive:!0});let f=rd(Ce(u,"server.mjs")).mtimeMs,g=ke(Ce(m,"server.mjs"))?rd(Ce(m,"server.mjs")).mtimeMs:0;if(f>g&&(h.push("Copying source files..."),$B(u,m,{recursive:!0,force:!0}),h.push("Source files copied."),p=!0),!ke(Ce(m,"node_modules"))||p){h.push("Installing dependencies (first run, ~30s)...");try{kP(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{td(Ce(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!ke(Ce(m,"node_modules","vite"))||!ke(Ce(m,"node_modules","better-sqlite3")))throw td(Ce(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");h.push("Dependencies installed.")}h.push("Building dashboard..."),kP("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),h.push("Build complete.");let _=!1;try{let{request:k}=await import("node:http");await new Promise((P,N)=>{let R=k(`http://127.0.0.1:${s}/api/overview`,{timeout:2e3},O=>{O.resume(),P()});R.on("error",()=>N()),R.on("timeout",()=>{R.destroy(),N()}),R.end()}),_=!0}catch{}if(_&&p){h.push("Killing stale dashboard server (source updated)...");let k=G_(s);if(k.attemptedPids.length>0&&k.killedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Could not free port ${s} (kill failed for ${k.attemptedPids.join(", ")}: ${k.errors.join("; ")}). Try ctx_insight({ port: ${s+1} }) or stop the process manually.`}]});if(k.errors.length>0&&k.attemptedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${s}: ${k.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(P=>setTimeout(P,500)),h.push(`Stale server killed (${k.killedPids.length} pid${k.killedPids.length===1?"":"s"}).`)}else if(_){h.push("Dashboard already running.");let k=`http://localhost:${s}`,P=F_(k),N=P.ok?"":` (auto-open failed: ${P.reason}; navigate manually)`;return W("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${k}${N}`}]})}if(pn&&pn.pid&&!pn.killed)try{pn.kill("SIGTERM")}catch{}let{spawn:b}=await import("node:child_process"),v=b("node",[Ce(m,"server.mjs")],{cwd:m,env:{...process.env,PORT:String(s),INSIGHT_SESSION_DIR:l,INSIGHT_CONTENT_DIR:d,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});v.on("error",()=>{}),v.unref(),pn=v,await new Promise(k=>setTimeout(k,1500));try{let{request:k}=await import("node:http");await new Promise((P,N)=>{let R=k(`http://127.0.0.1:${s}/api/overview`,{timeout:3e3},O=>{P(),O.resume()});R.on("error",N),R.on("timeout",()=>{R.destroy(),N(new Error("timeout"))}),R.end()})}catch{return W("ctx_insight",{content:[{type:"text",text:`Port ${s} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
1072
1121
 
1073
1122
  To fix:
1074
1123
  - Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${s}`:`lsof -ti:${s} | xargs kill`}
1075
- - Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let x=`http://localhost:${s}`,P=p_(x),E=P.ok?"":` (auto-open failed: ${P.reason}; navigate manually)`;return f.push(`Dashboard running at ${x}${E}`),G("ctx_insight",{content:[{type:"text",text:f.map(R=>`- ${R}`).join(`
1124
+ - Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let E=`http://localhost:${s}`,C=F_(E),x=C.ok?"":` (auto-open failed: ${C.reason}; navigate manually)`;return h.push(`Dashboard running at ${E}${x}`),W("ctx_insight",{content:[{type:"text",text:h.map(k=>`- ${k}`).join(`
1076
1125
  `)+`
1077
1126
 
1078
- Open: ${x}
1079
- PID: ${b.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${b.pid} /F`:`kill ${b.pid}`}`}]})}catch(f){let p=f instanceof Error?f.message:String(f);return G("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&XH().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var hP={};Le(hP,{needsHookNormalization:()=>La,normalizeHooksJson:()=>mP,normalizeHooksOnStartup:()=>QH,normalizePluginJson:()=>fP});import{existsSync as uP,readFileSync as lP,writeFileSync as dP}from"node:fs";import{resolve as pP}from"node:path";function Hn(t){return String(t).replace(/\\/g,"/")}function b_(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(Hn(t));return e?e[1]:null}function x_(t,e){if(!e||!t||typeof t!="string")return!1;let r=Hn(t);Vl.lastIndex=0;let n;for(;(n=Vl.exec(r))!==null;)if(n[1]!==e)return!0;return!1}function La(t,e){return!t||typeof t!="string"?!1:t.includes(za)?!0:x_(t,b_(e))}function mP(t,e,r){if(!La(t,r))return t;let n=Hn(e),o=Hn(r),s=b_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.hooks;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let d=a[u];if(Array.isArray(d))for(let l of d){let m=l?.hooks;if(Array.isArray(m))for(let f of m){if(typeof f?.command!="string")continue;let p=f.command.includes(za),h=x_(f.command,s);if(!p&&!h)continue;let g=f.command;p&&(g=g.replaceAll(za,o),g=g.replace(/^\s*node\s+/,`"${n}" `)),h&&(g=Hn(g).replace(Vl,`context-mode/context-mode/${s}`)),f.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function fP(t,e,r){if(!La(t,r))return t;let n=Hn(e),o=Hn(r),s=b_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.mcpServers;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let d=a[u];if(!(!d||typeof d!="object")){if(Array.isArray(d.args)){let l=d.args,m=l.map(f=>{if(typeof f!="string")return f;let p=f;return p.includes(za)&&(p=p.replaceAll(za,o)),x_(p,s)&&(p=Hn(p).replace(Vl,`context-mode/context-mode/${s}`)),p});m.some((f,p)=>f!==l[p])&&(d.args=m,c=!0)}d.command==="node"&&c&&(d.command=n)}}return c?JSON.stringify(i,null,2):t}function QH({pluginRoot:t,nodePath:e,platform:r}){if(!(r!=="win32"&&r!=="linux")&&!(!t||!e)){try{let n=pP(t,"hooks","hooks.json");if(uP(n)){let o=lP(n,"utf-8");if(La(o,t)){let s=mP(o,e,t);s!==o&&dP(n,s,"utf-8")}}}catch{}try{let n=pP(t,".claude-plugin","plugin.json");if(uP(n)){let o=lP(n,"utf-8");if(La(o,t)){let s=fP(o,e,t);s!==o&&dP(n,s,"utf-8")}}}catch{}}}var za,Vl,gP=S(()=>{"use strict";za="${CLAUDE_PLUGIN_ROOT}",Vl=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});import{stdout as WP,stdin as GP}from"node:process";import*as sn from"node:readline";var $_=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,T_=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,P_=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var td=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ha=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Za=/\t{1,1000}/y,rd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Ba=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MP=new RegExp("\\p{M}+","gu"),jP={limit:1/0,ellipsis:""},R_=(t,e={},r={})=>{let n=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?R_(o,jP,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,m=r.regularWidth??1,f=r.wideWidth??2,p=0,h=0,g=t.length,y=0,v=!1,_=g,b=Math.max(0,n-s),x=0,P=0,E=0,R=0;e:for(;;){if(P>x||h>=g&&h>p){let A=t.slice(x,P)||t.slice(p,h);y=0;for(let L of A.replaceAll(MP,"")){let w=L.codePointAt(0)||0;if(T_(w)?R=l:P_(w)?R=f:u!==m&&$_(w)?R=u:R=m,E+R>b&&(_=Math.min(_,Math.max(x,p)+y)),E+R>n){v=!0;break e}y+=L.length,E+=R}x=P=0}if(h>=g)break;if(Ba.lastIndex=h,Ba.test(t)){if(y=Ba.lastIndex-h,R=y*m,E+R>b&&(_=Math.min(_,h+Math.floor((b-E)/m))),E+R>n){v=!0;break}E+=R,x=p,P=h,h=p=Ba.lastIndex;continue}if(td.lastIndex=h,td.test(t)){if(E+i>b&&(_=Math.min(_,h)),E+i>n){v=!0;break}E+=i,x=p,P=h,h=p=td.lastIndex;continue}if(Ha.lastIndex=h,Ha.test(t)){if(y=Ha.lastIndex-h,R=y*a,E+R>b&&(_=Math.min(_,h+Math.floor((b-E)/a))),E+R>n){v=!0;break}E+=R,x=p,P=h,h=p=Ha.lastIndex;continue}if(Za.lastIndex=h,Za.test(t)){if(y=Za.lastIndex-h,R=y*c,E+R>b&&(_=Math.min(_,h+Math.floor((b-E)/c))),E+R>n){v=!0;break}E+=R,x=p,P=h,h=p=Za.lastIndex;continue}if(rd.lastIndex=h,rd.test(t)){if(E+d>b&&(_=Math.min(_,h)),E+d>n){v=!0;break}E+=d,x=p,P=h,h=p=rd.lastIndex;continue}h+=1}return{width:v?b:E,index:v?_:g,truncated:v,ellipsed:v&&n>=s}},C_=R_;var zP={limit:1/0,ellipsis:"",ellipsisWidth:0},LP=(t,e={})=>C_(t,zP,e).width,ht=LP;var qa="\x1B",D_="\x9B",FP=39,od="\x07",M_="[",UP="]",j_="m",sd=`${UP}8;;`,O_=new RegExp(`(?:\\${M_}(?<code>\\d+)m|\\${sd}(?<uri>.*)${od})`,"y"),I_=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},A_=t=>`${qa}${M_}${t}${j_}`,N_=t=>`${qa}${sd}${t}${od}`,nd=(t,e,r)=>{let n=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:ht(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,m=ht(l);a+m<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===qa||l===D_)&&(o=!0,s=e.startsWith(sd,d+1)),o?s?l===od&&(o=!1,s=!1):l===j_&&(o=!1):(a+=m,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},HP=t=>{let e=t.split(" "),r=e.length;for(;r&&!ht(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},ZP=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",o,s,i=t.split(" "),a=[""],c=0;for(let l=0;l<i.length;l++){let m=i[l];if(r.trim!==!1){let p=a.at(-1)??"",h=p.trimStart();p.length!==h.length&&(a[a.length-1]=h,c=ht(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=ht(m);if(r.hard&&f>e){let p=e-c,h=1+Math.floor((f-p-1)/e);Math.floor((f-1)/e)<h&&a.push(""),nd(a,m,e),c=ht(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){nd(a,m,e),c=ht(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){nd(a,m,e),c=ht(a.at(-1)??"");continue}a[a.length-1]+=m,c+=f}r.trim!==!1&&(a=a.map(l=>HP(l)));let u=a.join(`
1080
- `),d=!1;for(let l=0;l<u.length;l++){let m=u[l];if(n+=m,!d)d=m>="\uD800"&&m<="\uDBFF";else continue;if(m===qa||m===D_){O_.lastIndex=l+1;let p=O_.exec(u)?.groups;if(p?.code!==void 0){let h=Number.parseFloat(p.code);o=h===FP?void 0:h}else p?.uri!==void 0&&(s=p.uri.length===0?void 0:p.uri)}if(u[l+1]===`
1081
- `){s&&(n+=N_(""));let f=o?I_(o):void 0;o&&f&&(n+=A_(f))}else m===`
1082
- `&&(o&&I_(o)&&(n+=A_(o)),s&&(n+=N_(s)))}return n},BP=/\r?\n/;function zo(t,e,r){return String(t).normalize().split(BP).map(n=>ZP(n,e,r)).join(`
1083
- `)}var ti=ei(ad(),1);import{ReadStream as L_}from"node:tty";var KP=["up","down","left","right","space","enter","cancel"],JP=["January","February","March","April","May","June","July","August","September","October","November","December"],Er={actions:new Set(KP),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...JP],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function F_(t,e){if(typeof t=="string")return Er.aliases.get(t)===e;for(let r of t)if(r!==void 0&&F_(r,e))return!0;return!1}var YP=globalThis.process.platform.startsWith("win");function U_({input:t=GP,output:e=WP,overwrite:r=!0,hideCursor:n=!0}={}){let o=sn.createInterface({input:t,output:e,prompt:"",tabSize:1});sn.emitKeypressEvents(t,o),t instanceof L_&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(F_([u,a,c],"cancel")){n&&e.write(ti.cursor.show),process.exit(0);return}if(!r)return;sn.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{sn.clearLine(e,1,()=>{t.once("keypress",s)})})};return n&&e.write(ti.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),n&&e.write(ti.cursor.show),t instanceof L_&&t.isTTY&&!YP&&t.setRawMode(!1),o.terminal=!1,o.close()}}var cd=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Ae,stripVTControlCharacters as XZ}from"node:util";import Ht from"node:process";var ri=ei(ad(),1);function QP(){return Ht.platform!=="win32"?Ht.env.TERM!=="linux":!!Ht.env.CI||!!Ht.env.WT_SESSION||!!Ht.env.TERMINUS_SUBLIME||Ht.env.ConEmuTask==="{cmd::Cmder}"||Ht.env.TERM_PROGRAM==="Terminus-Sublime"||Ht.env.TERM_PROGRAM==="vscode"||Ht.env.TERM==="xterm-256color"||Ht.env.TERM==="alacritty"||Ht.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ud=QP(),eR=()=>process.env.CI==="true";var ye=(t,e)=>ud?t:e,rB=ye("\u25C6","*"),tR=ye("\u25A0","x"),rR=ye("\u25B2","x"),ld=ye("\u25C7","o"),nR=ye("\u250C","T"),an=ye("\u2502","|"),oR=ye("\u2514","\u2014"),nB=ye("\u2510","T"),oB=ye("\u2518","\u2014"),sB=ye("\u25CF",">"),iB=ye("\u25CB"," "),aB=ye("\u25FB","[\u2022]"),cB=ye("\u25FC","[+]"),uB=ye("\u25FB","[ ]"),lB=ye("\u25AA","\u2022"),H_=ye("\u2500","-"),sR=ye("\u256E","+"),iR=ye("\u251C","+"),aR=ye("\u256F","+"),cR=ye("\u2570","+"),dB=ye("\u256D","+"),uR=ye("\u25CF","\u2022"),lR=ye("\u25C6","*"),dR=ye("\u25B2","!"),pR=ye("\u25A0","x");var C={message:(t=[],{symbol:e=Ae("gray",an),secondarySymbol:r=Ae("gray",an),output:n=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Er.withGuide,c=a?r:"",u=a?`${e} `:"",d=a?`${r} `:"";for(let m=0;m<o;m++)i.push(c);let l=Array.isArray(t)?t:t.split(`
1084
- `);if(l.length>0){let[m,...f]=l;m.length>0?i.push(`${u}${m}`):i.push(a?e:"");for(let p of f)p.length>0?i.push(`${d}${p}`):i.push(a?r:"")}n.write(`${i.join(`
1127
+ Open: ${E}
1128
+ PID: ${v.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${v.pid} /F`:`kill ${v.pid}`}`}]})}catch(h){let p=h instanceof Error?h.message:String(h);return W("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&SZ().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var lR={};we(lR,{needsHookNormalization:()=>oc,normalizeHooksJson:()=>aR,normalizeHooksJsonOnly:()=>uR,normalizeHooksOnStartup:()=>kZ,normalizePluginJson:()=>cR});import{existsSync as nR,readFileSync as oR,writeFileSync as sR}from"node:fs";import{resolve as iR}from"node:path";function Gn(t){return String(t).replace(/\\/g,"/")}function J_(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(Gn(t));return e?e[1]:null}function X_(t,e){if(!e||!t||typeof t!="string")return!1;let r=Gn(t);cd.lastIndex=0;let n;for(;(n=cd.exec(r))!==null;)if(n[1]!==e)return!0;return!1}function oc(t,e){return!t||typeof t!="string"?!1:t.includes(nc)?!0:X_(t,J_(e))}function aR(t,e,r){if(!oc(t,r))return t;let n=Gn(e),o=Gn(r),s=J_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.hooks;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(Array.isArray(l))for(let d of l){let m=d?.hooks;if(Array.isArray(m))for(let h of m){if(typeof h?.command!="string")continue;let p=h.command.includes(nc),f=X_(h.command,s);if(!p&&!f)continue;let g=h.command;p&&(g=g.replaceAll(nc,o),g=g.replace(/^\s*node\s+/,`"${n}" `)),f&&(g=Gn(g).replace(cd,`context-mode/context-mode/${s}`)),h.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function cR(t,e,r){if(!oc(t,r))return t;let n=Gn(e),o=Gn(r),s=J_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.mcpServers;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(!(!l||typeof l!="object")){if(Array.isArray(l.args)){let d=l.args,m=d.map(h=>{if(typeof h!="string")return h;let p=h;return p.includes(nc)&&(p=p.replaceAll(nc,o)),X_(p,s)&&(p=Gn(p).replace(cd,`context-mode/context-mode/${s}`)),p});m.some((h,p)=>h!==d[p])&&(l.args=m,c=!0)}l.command==="node"&&c&&(l.command=n)}}return c?JSON.stringify(i,null,2):t}function uR({pluginRoot:t,nodePath:e,jsRuntimePath:r,platform:n}){let o=r||e;if(!(n!=="win32"&&n!=="linux"&&!(r&&r!==e))&&!(!t||!o))try{let a=iR(t,"hooks","hooks.json");if(nR(a)){let c=oR(a,"utf-8");if(oc(c,t)){let u=aR(c,o,t);u!==c&&sR(a,u,"utf-8")}}}catch{}}function kZ({pluginRoot:t,nodePath:e,jsRuntimePath:r,platform:n}){if(uR({pluginRoot:t,nodePath:e,jsRuntimePath:r,platform:n}),!(n!=="win32"&&n!=="linux")&&!(!t||!e))try{let o=iR(t,".claude-plugin","plugin.json");if(nR(o)){let s=oR(o,"utf-8");if(oc(s,t)){let i=cR(s,e,t);i!==s&&sR(o,i,"utf-8")}}}catch{}}var nc,cd,dR=S(()=>{"use strict";nc="${CLAUDE_PLUGIN_ROOT}",cd=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});var bR={};we(bR,{buildHookCommand:()=>gR,ensureShebangAndExecBit:()=>_R,extractNodePath:()=>fR,isStaleNodePath:()=>hR,rewriteShellSnapshots:()=>yR,selfHealCacheHealHook:()=>RZ,selfHealShellSnapshots:()=>CZ});import{existsSync as sc,readFileSync as Y_,writeFileSync as Q_,chmodSync as wZ,statSync as mR,readdirSync as EZ,renameSync as $Z,unlinkSync as TZ}from"node:fs";import{join as PZ}from"node:path";function pR(t){return String(t).replace(/\\/g,"/")}function fR(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e)return null;let r;if(e.startsWith('"')){let o=e.indexOf('"',1);if(o===-1)return null;r=e.slice(1,o)}else{let o=e.search(/\s/);r=o===-1?e:e.slice(0,o)}if(!r)return null;let n=r.split(/[\\/]/).pop()??"";return/^node(\.exe)?$/i.test(n)?r:null}function hR(t){let e=fR(t);if(!e)return!1;try{return!sc(e)}catch{return!1}}function gR({scriptPath:t,platform:e,nodePath:r}){if(!t||typeof t!="string")throw new TypeError("buildHookCommand: scriptPath is required");let n=pR(t);if(e==="win32"){if(!r||typeof r!="string")throw new TypeError("buildHookCommand: nodePath is required on win32");return`"${pR(r)}" "${n}"`}return`"${n}"`}function RZ({settingsPath:t,scriptPath:e,platform:r,nodePath:n}){if(!t||!sc(t))return"missing-settings";let o;try{o=Y_(t,"utf-8")}catch{return"noop"}let s;try{s=JSON.parse(o)}catch{return"noop"}let i=s?.hooks;if(!i||typeof i!="object")return"noop";let a=Array.isArray(i.SessionStart)?i.SessionStart:null;if(!a)return"noop";let c=!1;for(let u of a){let l=u?.hooks;if(Array.isArray(l))for(let d of l)typeof d?.command=="string"&&d.command.includes("context-mode-cache-heal")&&hR(d.command)&&(d.command=gR({scriptPath:e,platform:r,nodePath:n}),c=!0)}if(!c)return"noop";if(r!=="win32"&&e&&sc(e))try{_R(e)}catch{}try{Q_(t,JSON.stringify(s,null,2)+`
1129
+ `,"utf-8")}catch{return"noop"}return"healed"}function yR({snapshotsDir:t,currentVersion:e}){let r={rewritten:[]};if(!t||typeof t!="string"||!e||typeof e!="string")return r;let n;try{if(!sc(t))return r;n=EZ(t)}catch{return r}let o=/(context-mode[/\\]context-mode[/\\])([^/\\]+)([/\\]bin)/g;for(let s of n){if(!s.endsWith(".sh"))continue;let i=PZ(t,s),a;try{if(!mR(i).isFile())continue;a=Y_(i,"utf-8")}catch{continue}let c=!1,u=a.replace(o,(d,m,h,p)=>h===e?d:(c=!0,`${m}${e}${p}`));if(!c)continue;let l=`${i}.tmp-${process.pid}-${Date.now()}`;try{Q_(l,u,"utf-8"),$Z(l,i),r.rewritten.push(i)}catch{try{TZ(l)}catch{}}}return r}function CZ({snapshotsDir:t,pluginCacheRoot:e,currentVersion:r}){return yR({snapshotsDir:t,currentVersion:r})}function _R(t){if(!(!t||!sc(t)))try{let e=Y_(t,"utf-8");e.startsWith("#!")||Q_(t,`#!/usr/bin/env node
1130
+ ${e}`,"utf-8"),(mR(t).mode&511)!==493&&wZ(t,493)}catch{}}var xR=S(()=>{"use strict"});import{stdout as tC,stdin as rC}from"node:process";import*as hn from"node:readline";var ib=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,ab=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,cb=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var _d=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,cc=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,uc=/\t{1,1000}/y,bd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),lc=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ZR=new RegExp("\\p{M}+","gu"),qR={limit:1/0,ellipsis:""},ub=(t,e={},r={})=>{let n=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?ub(o,qR,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,l=r.emojiWidth??2,d=r.fullWidthWidth??2,m=r.regularWidth??1,h=r.wideWidth??2,p=0,f=0,g=t.length,y=0,_=!1,b=g,v=Math.max(0,n-s),E=0,C=0,x=0,k=0;e:for(;;){if(C>E||f>=g&&f>p){let P=t.slice(E,C)||t.slice(p,f);y=0;for(let N of P.replaceAll(ZR,"")){let R=N.codePointAt(0)||0;if(ab(R)?k=d:cb(R)?k=h:u!==m&&ib(R)?k=u:k=m,x+k>v&&(b=Math.min(b,Math.max(E,p)+y)),x+k>n){_=!0;break e}y+=N.length,x+=k}E=C=0}if(f>=g)break;if(lc.lastIndex=f,lc.test(t)){if(y=lc.lastIndex-f,k=y*m,x+k>v&&(b=Math.min(b,f+Math.floor((v-x)/m))),x+k>n){_=!0;break}x+=k,E=p,C=f,f=p=lc.lastIndex;continue}if(_d.lastIndex=f,_d.test(t)){if(x+i>v&&(b=Math.min(b,f)),x+i>n){_=!0;break}x+=i,E=p,C=f,f=p=_d.lastIndex;continue}if(cc.lastIndex=f,cc.test(t)){if(y=cc.lastIndex-f,k=y*a,x+k>v&&(b=Math.min(b,f+Math.floor((v-x)/a))),x+k>n){_=!0;break}x+=k,E=p,C=f,f=p=cc.lastIndex;continue}if(uc.lastIndex=f,uc.test(t)){if(y=uc.lastIndex-f,k=y*c,x+k>v&&(b=Math.min(b,f+Math.floor((v-x)/c))),x+k>n){_=!0;break}x+=k,E=p,C=f,f=p=uc.lastIndex;continue}if(bd.lastIndex=f,bd.test(t)){if(x+l>v&&(b=Math.min(b,f)),x+l>n){_=!0;break}x+=l,E=p,C=f,f=p=bd.lastIndex;continue}f+=1}return{width:_?v:x,index:_?b:g,truncated:_,ellipsed:_&&n>=s}},lb=ub;var VR={limit:1/0,ellipsis:"",ellipsisWidth:0},WR=(t,e={})=>lb(t,VR,e).width,bt=WR;var dc="\x1B",hb="\x9B",KR=39,vd="\x07",gb="[",GR="]",yb="m",Sd=`${GR}8;;`,db=new RegExp(`(?:\\${gb}(?<code>\\d+)m|\\${Sd}(?<uri>.*)${vd})`,"y"),pb=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},mb=t=>`${dc}${gb}${t}${yb}`,fb=t=>`${dc}${Sd}${t}${vd}`,xd=(t,e,r)=>{let n=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:bt(i),c=n.next(),u=n.next(),l=0;for(;!c.done;){let d=c.value,m=bt(d);a+m<=r?t[t.length-1]+=d:(t.push(d),a=0),(d===dc||d===hb)&&(o=!0,s=e.startsWith(Sd,l+1)),o?s?d===vd&&(o=!1,s=!1):d===yb&&(o=!1):(a+=m,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),l+=d.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},JR=t=>{let e=t.split(" "),r=e.length;for(;r&&!bt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},XR=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let m=i[d];if(r.trim!==!1){let p=a.at(-1)??"",f=p.trimStart();p.length!==f.length&&(a[a.length-1]=f,c=bt(f))}d!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let h=bt(m);if(r.hard&&h>e){let p=e-c,f=1+Math.floor((h-p-1)/e);Math.floor((h-1)/e)<f&&a.push(""),xd(a,m,e),c=bt(a.at(-1)??"");continue}if(c+h>e&&c&&h){if(r.wordWrap===!1&&c<e){xd(a,m,e),c=bt(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>e&&r.wordWrap===!1){xd(a,m,e),c=bt(a.at(-1)??"");continue}a[a.length-1]+=m,c+=h}r.trim!==!1&&(a=a.map(d=>JR(d)));let u=a.join(`
1131
+ `),l=!1;for(let d=0;d<u.length;d++){let m=u[d];if(n+=m,!l)l=m>="\uD800"&&m<="\uDBFF";else continue;if(m===dc||m===hb){db.lastIndex=d+1;let p=db.exec(u)?.groups;if(p?.code!==void 0){let f=Number.parseFloat(p.code);o=f===KR?void 0:f}else p?.uri!==void 0&&(s=p.uri.length===0?void 0:p.uri)}if(u[d+1]===`
1132
+ `){s&&(n+=fb(""));let h=o?pb(o):void 0;o&&h&&(n+=mb(h))}else m===`
1133
+ `&&(o&&pb(o)&&(n+=mb(o)),s&&(n+=fb(s)))}return n},YR=/\r?\n/;function Jo(t,e,r){return String(t).normalize().split(YR).map(n=>XR(n,e,r)).join(`
1134
+ `)}var xi=bi(wd(),1);import{ReadStream as bb}from"node:tty";var nC=["up","down","left","right","space","enter","cancel"],oC=["January","February","March","April","May","June","July","August","September","October","November","December"],Rr={actions:new Set(nC),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...oC],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function xb(t,e){if(typeof t=="string")return Rr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&xb(r,e))return!0;return!1}var sC=globalThis.process.platform.startsWith("win");function vb({input:t=rC,output:e=tC,overwrite:r=!0,hideCursor:n=!0}={}){let o=hn.createInterface({input:t,output:e,prompt:"",tabSize:1});hn.emitKeypressEvents(t,o),t instanceof bb&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(xb([u,a,c],"cancel")){n&&e.write(xi.cursor.show),process.exit(0);return}if(!r)return;hn.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{hn.clearLine(e,1,()=>{t.once("keypress",s)})})};return n&&e.write(xi.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),n&&e.write(xi.cursor.show),t instanceof bb&&t.isTTY&&!sC&&t.setRawMode(!1),o.terminal=!1,o.close()}}var Ed=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as De,stripVTControlCharacters as Mq}from"node:util";import Vt from"node:process";var vi=bi(wd(),1);function aC(){return Vt.platform!=="win32"?Vt.env.TERM!=="linux":!!Vt.env.CI||!!Vt.env.WT_SESSION||!!Vt.env.TERMINUS_SUBLIME||Vt.env.ConEmuTask==="{cmd::Cmder}"||Vt.env.TERM_PROGRAM==="Terminus-Sublime"||Vt.env.TERM_PROGRAM==="vscode"||Vt.env.TERM==="xterm-256color"||Vt.env.TERM==="alacritty"||Vt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var $d=aC(),cC=()=>process.env.CI==="true";var _e=(t,e)=>$d?t:e,Fq=_e("\u25C6","*"),uC=_e("\u25A0","x"),lC=_e("\u25B2","x"),Td=_e("\u25C7","o"),dC=_e("\u250C","T"),gn=_e("\u2502","|"),pC=_e("\u2514","\u2014"),Hq=_e("\u2510","T"),Uq=_e("\u2518","\u2014"),Bq=_e("\u25CF",">"),Zq=_e("\u25CB"," "),qq=_e("\u25FB","[\u2022]"),Vq=_e("\u25FC","[+]"),Wq=_e("\u25FB","[ ]"),Kq=_e("\u25AA","\u2022"),Sb=_e("\u2500","-"),mC=_e("\u256E","+"),fC=_e("\u251C","+"),hC=_e("\u256F","+"),gC=_e("\u2570","+"),Gq=_e("\u256D","+"),yC=_e("\u25CF","\u2022"),_C=_e("\u25C6","*"),bC=_e("\u25B2","!"),xC=_e("\u25A0","x");var I={message:(t=[],{symbol:e=De("gray",gn),secondarySymbol:r=De("gray",gn),output:n=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Rr.withGuide,c=a?r:"",u=a?`${e} `:"",l=a?`${r} `:"";for(let m=0;m<o;m++)i.push(c);let d=Array.isArray(t)?t:t.split(`
1135
+ `);if(d.length>0){let[m,...h]=d;m.length>0?i.push(`${u}${m}`):i.push(a?e:"");for(let p of h)p.length>0?i.push(`${l}${p}`):i.push(a?r:"")}n.write(`${i.join(`
1085
1136
  `)}
1086
- `)},info:(t,e)=>{C.message(t,{...e,symbol:Ae("blue",uR)})},success:(t,e)=>{C.message(t,{...e,symbol:Ae("green",lR)})},step:(t,e)=>{C.message(t,{...e,symbol:Ae("green",ld)})},warn:(t,e)=>{C.message(t,{...e,symbol:Ae("yellow",dR)})},warning:(t,e)=>{C.warn(t,e)},error:(t,e)=>{C.message(t,{...e,symbol:Ae("red",pR)})}};var dd=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Er.withGuide?`${Ae("gray",nR)} `:"";r.write(`${n}${t}
1087
- `)},Va=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Er.withGuide?`${Ae("gray",an)}
1088
- ${Ae("gray",oR)} `:"";r.write(`${n}${t}
1089
-
1090
- `)};var mR=t=>Ae("dim",t),fR=(t,e,r)=>{let n={hard:!0,trim:!1},o=zo(t,e,n).split(`
1091
- `),s=o.reduce((c,u)=>Math.max(ht(u),c),0),i=o.map(r).reduce((c,u)=>Math.max(ht(u),c),0),a=e-(i-s);return zo(t,a,n)},Wa=(t="",e="",r)=>{let n=r?.output??Ht.stdout,o=r?.withGuide??Er.withGuide,s=r?.format??mR,i=["",...fR(t,cd(n)-6,s).split(`
1092
- `).map(s),""],a=ht(e),c=Math.max(i.reduce((m,f)=>{let p=ht(f);return p>m?p:m},0),a)+2,u=i.map(m=>`${Ae("gray",an)} ${m}${" ".repeat(c-ht(m))}${Ae("gray",an)}`).join(`
1093
- `),d=o?`${Ae("gray",an)}
1094
- `:"",l=o?iR:cR;n.write(`${d}${Ae("green",ld)} ${Ae("reset",e)} ${Ae("gray",H_.repeat(Math.max(c-a-1,1))+sR)}
1137
+ `)},info:(t,e)=>{I.message(t,{...e,symbol:De("blue",yC)})},success:(t,e)=>{I.message(t,{...e,symbol:De("green",_C)})},step:(t,e)=>{I.message(t,{...e,symbol:De("green",Td)})},warn:(t,e)=>{I.message(t,{...e,symbol:De("yellow",bC)})},warning:(t,e)=>{I.warn(t,e)},error:(t,e)=>{I.message(t,{...e,symbol:De("red",xC)})}};var Pd=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Rr.withGuide?`${De("gray",dC)} `:"";r.write(`${n}${t}
1138
+ `)},pc=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Rr.withGuide?`${De("gray",gn)}
1139
+ ${De("gray",pC)} `:"";r.write(`${n}${t}
1140
+
1141
+ `)};var vC=t=>De("dim",t),SC=(t,e,r)=>{let n={hard:!0,trim:!1},o=Jo(t,e,n).split(`
1142
+ `),s=o.reduce((c,u)=>Math.max(bt(u),c),0),i=o.map(r).reduce((c,u)=>Math.max(bt(u),c),0),a=e-(i-s);return Jo(t,a,n)},mc=(t="",e="",r)=>{let n=r?.output??Vt.stdout,o=r?.withGuide??Rr.withGuide,s=r?.format??vC,i=["",...SC(t,Ed(n)-6,s).split(`
1143
+ `).map(s),""],a=bt(e),c=Math.max(i.reduce((m,h)=>{let p=bt(h);return p>m?p:m},0),a)+2,u=i.map(m=>`${De("gray",gn)} ${m}${" ".repeat(c-bt(m))}${De("gray",gn)}`).join(`
1144
+ `),l=o?`${De("gray",gn)}
1145
+ `:"",d=o?fC:gC;n.write(`${l}${De("green",Td)} ${De("reset",e)} ${De("gray",Sb.repeat(Math.max(c-a-1,1))+mC)}
1095
1146
  ${u}
1096
- ${Ae("gray",l+H_.repeat(c+2)+aR)}
1097
- `)};var hR=t=>Ae("magenta",t),pd=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:o,frames:s=ud?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=ud?80:120,signal:a,...c}={})=>{let u=eR(),d,l,m=!1,f=!1,p="",h,g=performance.now(),y=cd(r),v=c?.styleFrame??hR,_=te=>{let Ze=te>1?o??Er.messages.error:n??Er.messages.cancel;f=te===1,m&&(U(Ze,te),f&&typeof e=="function"&&e())},b=()=>_(2),x=()=>_(1),P=()=>{process.on("uncaughtExceptionMonitor",b),process.on("unhandledRejection",b),process.on("SIGINT",x),process.on("SIGTERM",x),process.on("exit",_),a&&a.addEventListener("abort",x)},E=()=>{process.removeListener("uncaughtExceptionMonitor",b),process.removeListener("unhandledRejection",b),process.removeListener("SIGINT",x),process.removeListener("SIGTERM",x),process.removeListener("exit",_),a&&a.removeEventListener("abort",x)},R=()=>{if(h===void 0)return;u&&r.write(`
1098
- `);let te=zo(h,y,{hard:!0,trim:!1}).split(`
1099
- `);te.length>1&&r.write(ri.cursor.up(te.length-1)),r.write(ri.cursor.to(0)),r.write(ri.erase.down())},A=te=>te.replace(/\.+$/,""),L=te=>{let Ze=(performance.now()-te)/1e3,ft=Math.floor(Ze/60),sr=Math.floor(Ze%60);return ft>0?`[${ft}m ${sr}s]`:`[${sr}s]`},w=c.withGuide??Er.withGuide,F=(te="")=>{m=!0,d=U_({output:r}),p=A(te),g=performance.now(),w&&r.write(`${Ae("gray",an)}
1100
- `);let Ze=0,ft=0;P(),l=setInterval(()=>{if(u&&p===h)return;R(),h=p;let sr=v(s[Ze]),Zn;if(u)Zn=`${sr} ${p}...`;else if(t==="timer")Zn=`${sr} ${p} ${L(g)}`;else{let Ua=".".repeat(Math.floor(ft)).slice(0,3);Zn=`${sr} ${p}${Ua}`}let Fa=zo(Zn,y,{hard:!0,trim:!1});r.write(Fa),Ze=Ze+1<s.length?Ze+1:0,ft=ft<4?ft+.125:0},i)},U=(te="",Ze=0,ft=!1)=>{if(!m)return;m=!1,clearInterval(l),R();let sr=Ze===0?Ae("green",ld):Ze===1?Ae("red",tR):Ae("red",rR);p=te??p,ft||(t==="timer"?r.write(`${sr} ${p} ${L(g)}
1101
- `):r.write(`${sr} ${p}
1102
- `)),E(),d()};return{start:F,stop:(te="")=>U(te,0),message:(te="")=>{p=A(te??p)},cancel:(te="")=>U(te,1),error:(te="")=>U(te,2),clear:()=>U("",0,!0),get isCancelled(){return f}}},pB={light:ye("\u2500","-"),heavy:ye("\u2501","="),block:ye("\u2588","#")};var mB=`${Ae("gray",an)} `;var k=ei(q_(),1);Qa();gd();hn();Tr();import{execFileSync as Xs,execSync as eZ,execFile as tZ}from"node:child_process";import{readFileSync as Lr,cpSync as yP,accessSync as _P,existsSync as Ie,readdirSync as rZ,rmSync as Qs,closeSync as nZ,openSync as oZ,chmodSync as sZ,constants as vP}from"node:fs";import{request as iZ}from"node:https";import{resolve as ae,dirname as bP,join as mt}from"node:path";import{tmpdir as aZ,devNull as cZ,homedir as Kl}from"node:os";import{fileURLToPath as uZ,pathToFileURL as Jl}from"node:url";import{execFileSync as $O}from"node:child_process";var TO="node.*plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs",PO=`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs' } | Select-Object -ExpandProperty ProcessId`,RO=(t,e)=>$O(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),CO=t=>{try{return process.kill(t,0),!0}catch{return!1}},OO=(t,e)=>{process.kill(t,e)};function IO(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||!/^\d+$/.test(n))continue;let o=Number.parseInt(n,10);Number.isFinite(o)&&o>0&&e.add(o)}return[...e]}function zb(t){let e=t.platform??process.platform,r=t.runCommand??RO,n="";try{e==="win32"?n=r("powershell",["-NoProfile","-Command",PO]):n=r("pgrep",["-f",TO])}catch{return[]}return IO(n).filter(o=>o!==t.ownPid&&o!==t.ownPpid)}function AO(t){return new Promise(e=>{setTimeout(e,t)})}async function Lb(t){let e=t.timeoutMs??1500,r=t.pollIntervalMs??100,n=t.isAlive??CO,o=t.sendSignal??OO,s={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return s;let i=new Set,a=new Set;for(let l of t.pids){n(l)&&(i.add(l),a.add(l));try{o(l,"SIGTERM")}catch(m){m?.code!=="ESRCH"&&a.delete(l)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await AO(r);for(let l of[...a])n(l)||(a.delete(l),u++)}let d=0;for(let l of a){try{o(l,"SIGKILL")}catch(m){if(m?.code==="ESRCH"){u++;continue}continue}i.has(l)&&d++}return{terminatedBySigterm:u,terminatedBySigkill:d,totalKilled:u+d}}bp();import{existsSync as UO}from"node:fs";import{execSync as HO,execFileSync as d9,spawnSync as p9}from"node:child_process";function Hb({platform:t=process.platform,existsSync:e=UO,exec:r=HO,now:n=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let o="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(o))return null;let i=r(`"${o}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=n()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
1103
- `)}catch{}return null}return i[1]}catch{return null}}yn();function lZ(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}var dZ={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"},"gemini-cli":{beforeagent:"hooks/gemini-cli/beforeagent.mjs",beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function pZ(t,e){try{nZ(2),oZ(cZ,"w")}catch{process.stderr.write=(()=>!0)}let r=dZ[t]?.[e];r||process.exit(1);let n=jo();await import(Jl(mt(n,r)).href)}var mZ=new Set(["opencode","kilo"]),xP=t=>t?mZ.has(t):!1,kt=process.argv.slice(2);function fZ(){console.log(["Usage:"," context-mode Start MCP server (stdio)"," context-mode doctor Diagnose runtime issues, hooks, FTS5, version"," context-mode upgrade Fix hooks, permissions, and settings"," context-mode hook <platform> <event> Dispatch a configured hook script"," context-mode statusline Print Claude Code status line","","Environment:"," CONTEXT_MODE_DIR=/absolute/path Override sessions/content storage root; empty is ignored, non-empty must be absolute"].join(`
1104
- `))}if(kt[0]==="--help"||kt[0]==="-h"||kt[0]==="help")fZ();else if(kt[0]==="doctor")bZ().then(t=>process.exit(t));else if(kt[0]==="upgrade"){let t=kt.indexOf("--platform"),e=t>=0&&kt[t+1]?kt[t+1]:void 0;SZ(e?{platform:e}:void 0).catch(r=>{let n=r instanceof Error?r.message:String(r);C.error(k.default.red(n)),process.exit(1)})}else kt[0]==="hook"?pZ(kt[1],kt[2]):kt[0]==="insight"?xZ(kt[1]?Number(kt[1]):4747):kt[0]==="statusline"?kZ():Promise.resolve().then(()=>(cP(),aP));function m8(t){return t.replace(/\\/g,"/")}var Yl=process.platform==="win32";function Wl(t,e={}){Xs(Yl?"npm.cmd":"npm",t,{...e,...Yl?{shell:!0}:{}})}function hZ(t,e={}){let r={...e,...Yl?{shell:!0}:{}};eZ(Yl?t.replace(/^npm /,"npm.cmd "):t,r)}function gZ(t,e=process.platform,r=tZ){let n={stdio:"ignore"},o=()=>console.error(`
1105
- Could not auto-open browser. Open manually: ${t}`),s=lZ(t,e),i=!1;for(let{cmd:a,args:c}of s)try{r(a,c,n),i=!0;break}catch{}i||o()}function yZ(){let t=uZ(import.meta.url),e=bP(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?ae(e,".."):e}function _Z(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?ae(r,t,...e):ae(Kl(),"AppData","Local",t,...e)}return ae(Kl(),".cache",t,...e)}function jo(){let t=Et().platform;return xP(t)?_Z(t):yZ()}function SP(){try{return JSON.parse(Lr(ae(jo(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function vZ(){return new Promise(t=>{let e=iZ("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function Gl(t){return t.envVar?t.envVar:"adapter default"}function S_(t){try{return mn(t),C.success(k.default.green(`Storage ${t.kind}: PASS`)+k.default.dim(` \u2014 ${t.path} (${Gl(t)})`)),0}catch(e){if(e instanceof cr)return C.error(k.default.red(`Storage ${t.kind}: FAIL`)+k.default.dim(` \u2014 ${li(e)}`)),1;throw e}}async function bZ(){process.stdout.isTTY&&console.clear();let t=Et(),e=await _i(t.platform);dd(k.default.bgMagenta(k.default.white(" context-mode doctor "))),C.info(`Platform: ${k.default.cyan(e.name)}`+k.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0;try{let y=pn(()=>e.getSessionDir()),v=qo(()=>y.path),_=ui(()=>y.path);Wa([`sessions: ${y.path} (${Gl(y)})`,`content: ${v.path} (${Gl(v)})`,`stats: ${_.path} (${Gl(_)})`].join(`
1106
- `),"Storage paths"),r+=S_(y),r+=S_(v),r+=S_(_)}catch(y){if(y instanceof cr)r++,C.error(k.default.red(`Storage ${y.kind}: FAIL`)+k.default.dim(` \u2014 ${li(y)}`));else throw y}let n=pd();n.start("Running diagnostics");let o,s;try{o=Lo(),s=Xa(o)}catch{return n.stop("Diagnostics partial"),C.warn(k.default.yellow("Could not detect runtimes")+k.default.dim(" \u2014 module may be missing, restart session after upgrade")),Va(k.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),Wa(Ya(o),"Runtimes");{let{hasModernSqlite:y}=await Promise.resolve().then(()=>(ln(),vd));process.platform==="linux"&&!y()&&!Bn()&&(r++,C.error(k.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+k.default.dim(`
1147
+ ${De("gray",d+Sb.repeat(c+2)+hC)}
1148
+ `)};var kC=t=>De("magenta",t),Rd=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:o,frames:s=$d?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=$d?80:120,signal:a,...c}={})=>{let u=cC(),l,d,m=!1,h=!1,p="",f,g=performance.now(),y=Ed(r),_=c?.styleFrame??kC,b=K=>{let ge=K>1?o??Rr.messages.error:n??Rr.messages.cancel;h=K===1,m&&(F(ge,K),h&&typeof e=="function"&&e())},v=()=>b(2),E=()=>b(1),C=()=>{process.on("uncaughtExceptionMonitor",v),process.on("unhandledRejection",v),process.on("SIGINT",E),process.on("SIGTERM",E),process.on("exit",b),a&&a.addEventListener("abort",E)},x=()=>{process.removeListener("uncaughtExceptionMonitor",v),process.removeListener("unhandledRejection",v),process.removeListener("SIGINT",E),process.removeListener("SIGTERM",E),process.removeListener("exit",b),a&&a.removeEventListener("abort",E)},k=()=>{if(f===void 0)return;u&&r.write(`
1149
+ `);let K=Jo(f,y,{hard:!0,trim:!1}).split(`
1150
+ `);K.length>1&&r.write(vi.cursor.up(K.length-1)),r.write(vi.cursor.to(0)),r.write(vi.erase.down())},P=K=>K.replace(/\.+$/,""),N=K=>{let ge=(performance.now()-K)/1e3,We=Math.floor(ge/60),_t=Math.floor(ge%60);return We>0?`[${We}m ${_t}s]`:`[${_t}s]`},R=c.withGuide??Rr.withGuide,O=(K="")=>{m=!0,l=vb({output:r}),p=P(K),g=performance.now(),R&&r.write(`${De("gray",gn)}
1151
+ `);let ge=0,We=0;C(),d=setInterval(()=>{if(u&&p===f)return;k(),f=p;let _t=_(s[ge]),Pr;if(u)Pr=`${_t} ${p}...`;else if(t==="timer")Pr=`${_t} ${p} ${N(g)}`;else{let ac=".".repeat(Math.floor(We)).slice(0,3);Pr=`${_t} ${p}${ac}`}let ic=Jo(Pr,y,{hard:!0,trim:!1});r.write(ic),ge=ge+1<s.length?ge+1:0,We=We<4?We+.125:0},i)},F=(K="",ge=0,We=!1)=>{if(!m)return;m=!1,clearInterval(d),k();let _t=ge===0?De("green",Td):ge===1?De("red",uC):De("red",lC);p=K??p,We||(t==="timer"?r.write(`${_t} ${p} ${N(g)}
1152
+ `):r.write(`${_t} ${p}
1153
+ `)),x(),l()};return{start:O,stop:(K="")=>F(K,0),message:(K="")=>{p=P(K??p)},cancel:(K="")=>F(K,1),error:(K="")=>F(K,2),clear:()=>F("",0,!0),get isCancelled(){return h}}},Jq={light:_e("\u2500","-"),heavy:_e("\u2501","="),block:_e("\u2588","#")};var Xq=`${De("gray",gn)} `;var w=bi(Eb(),1);Xo();Ld();kn();Jt();Gp();Qp();import{execFileSync as yi,execSync as OZ,execFile as IZ}from"node:child_process";import{readFileSync as Wr,cpSync as vR,accessSync as wR,existsSync as $e,readdirSync as AZ,rmSync as _i,closeSync as NZ,openSync as DZ,chmodSync as MZ,lstatSync as jZ,realpathSync as dd,statSync as ER,constants as $R}from"node:fs";import{request as LZ}from"node:https";import{resolve as Q,dirname as rb,join as yt,sep as Kr,basename as zZ,isAbsolute as FZ}from"node:path";import{tmpdir as HZ,devNull as UZ,homedir as pd}from"node:os";import{fileURLToPath as BZ,pathToFileURL as md}from"node:url";import{execFileSync as EA}from"node:child_process";var $A="node.*plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs",TA=`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs' } | Select-Object -ExpandProperty ProcessId`,PA=(t,e)=>EA(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),RA=t=>{try{return process.kill(t,0),!0}catch{return!1}},CA=(t,e)=>{process.kill(t,e)};function OA(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||!/^\d+$/.test(n))continue;let o=Number.parseInt(n,10);Number.isFinite(o)&&o>0&&e.add(o)}return[...e]}function Wv(t){let e=t.platform??process.platform,r=t.runCommand??PA,n="";try{e==="win32"?n=r("powershell",["-NoProfile","-Command",TA]):n=r("pgrep",["-f",$A])}catch{return[]}return OA(n).filter(o=>o!==t.ownPid&&o!==t.ownPpid)}function IA(t){return new Promise(e=>{setTimeout(e,t)})}async function Kv(t){let e=t.timeoutMs??1500,r=t.pollIntervalMs??100,n=t.isAlive??RA,o=t.sendSignal??CA,s={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return s;let i=new Set,a=new Set;for(let d of t.pids){n(d)&&(i.add(d),a.add(d));try{o(d,"SIGTERM")}catch(m){m?.code!=="ESRCH"&&a.delete(d)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await IA(r);for(let d of[...a])n(d)||(a.delete(d),u++)}let l=0;for(let d of a){try{o(d,"SIGKILL")}catch(m){if(m?.code==="ESRCH"){u++;continue}continue}i.has(d)&&l++}return{terminatedBySigterm:u,terminatedBySigkill:l,totalKilled:u+l}}em();import{existsSync as FA}from"node:fs";import{execSync as HA,execFileSync as _3,spawnSync as b3}from"node:child_process";function Jv({platform:t=process.platform,existsSync:e=FA,exec:r=HA,now:n=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let o="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(o))return null;let i=r(`"${o}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=n()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
1154
+ `)}catch{}return null}return i[1]}catch{return null}}$n();Cr();function ZZ(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}var qZ={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"},"gemini-cli":{beforeagent:"hooks/gemini-cli/beforeagent.mjs",beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},kimi:{pretooluse:"hooks/kimi/pretooluse.mjs",posttooluse:"hooks/kimi/posttooluse.mjs",precompact:"hooks/kimi/precompact.mjs",sessionstart:"hooks/kimi/sessionstart.mjs",sessionend:"hooks/kimi/sessionend.mjs",userpromptsubmit:"hooks/kimi/userpromptsubmit.mjs",stop:"hooks/kimi/stop.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function VZ(t,e){try{NZ(2),DZ(UZ,"w")}catch{process.stderr.write=(()=>!0)}let r=qZ[t]?.[e];r||process.exit(1);let n=Go();await import(md(yt(n,r)).href)}var et=process.argv.slice(2);function WZ(){console.log(["Usage:"," context-mode Start MCP server (stdio)"," context-mode index <path> Index a file or directory into the FTS5 knowledge base"," context-mode search <query...> Search the current project's FTS5 knowledge base"," context-mode doctor Diagnose runtime issues, hooks, FTS5, version"," context-mode upgrade Fix hooks, permissions, and settings"," context-mode hook <platform> <event> Dispatch a configured hook script"," context-mode statusline Print Claude Code status line","","Index options:"," --source <label> Source label (default: project:<directory-name> or path)"," --project <path> Project identity for the content DB (default: indexed dir or cwd)"," --max-depth <n> Directory recursion depth (default: 5)"," --max-files <n> Directory file cap (default: 200)"," --ext <.ts,.md> Comma-separated extension allowlist"," --include <glob> Directory include pattern (repeatable)"," --exclude <glob> Directory exclude pattern (repeatable)"," --no-gitignore Do not apply .gitignore during directory walks"," --follow-symlinks Follow directory symlinks inside the root","","Search options:"," --project <path> Project identity for the content DB (default: cwd)"," --source <label> Filter to a source label (partial match)"," --limit <n> Results to show (default: 3)"," --type <code|prose> Filter by content type","","Environment:"," CONTEXT_MODE_DIR=/absolute/path Override sessions/content storage root; empty is ignored, non-empty must be absolute"].join(`
1155
+ `))}if(et[0]==="--help"||et[0]==="-h"||et[0]==="help")WZ();else if(et[0]==="index")rq(et.slice(1)).then(t=>process.exit(t));else if(et[0]==="search")nq(et.slice(1)).then(t=>process.exit(t));else if(et[0]==="doctor")oq().then(t=>process.exit(t));else if(et[0]==="upgrade"){let t=et.indexOf("--platform"),e=t>=0&&et[t+1]?et[t+1]:void 0;iq(e?{platform:e}:void 0).catch(r=>{let n=r instanceof Error?r.message:String(r);I.error(w.default.red(n)),process.exit(1)})}else et[0]==="hook"?VZ(et[1],et[2]):et[0]==="insight"?sq(et[1]?Number(et[1]):4747):et[0]==="statusline"?aq():Promise.resolve().then(()=>(rR(),tR));function gY(t){return t.replace(/\\/g,"/")}var fd=process.platform==="win32";function ud(t,e={}){yi(fd?"npm.cmd":"npm",t,{...e,...fd?{shell:!0}:{}})}function KZ(t,e={}){let r={...e,...fd?{shell:!0}:{}};OZ(fd?t.replace(/^npm /,"npm.cmd "):t,r)}function GZ(t,e=process.platform,r=IZ){let n={stdio:"ignore"},o=()=>console.error(`
1156
+ Could not auto-open browser. Open manually: ${t}`),s=ZZ(t,e),i=!1;for(let{cmd:a,args:c}of s)try{r(a,c,n),i=!0;break}catch{}i||o()}function JZ(){let t=BZ(import.meta.url),e=rb(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?Q(e,".."):e}function XZ(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?Q(r,t,...e):Q(pd(),"AppData","Local",t,...e)}return Q(pd(),".cache",t,...e)}function Go(){let t=vt().platform;return Xn(t)?XZ(t):JZ()}function TR(){try{return JSON.parse(Wr(Q(Go(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function YZ(){return new Promise(t=>{let e=LZ("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function ld(t){return t.envVar?t.envVar:"adapter default"}function PR(t){let e=[],r={};for(let n=0;n<t.length;n++){let o=t[n];if(!o.startsWith("--")||o==="--"){e.push(o);continue}let s=o.slice(2),i=s.indexOf("="),a=i>=0?s.slice(0,i):s,c=i>=0?s.slice(i+1):void 0,u=t[n+1],l=c!==void 0?c:u&&!u.startsWith("--")?(n++,u):!0;if(a==="include"||a==="exclude"){let d=r[a];r[a]=Array.isArray(d)?[...d,String(l)]:[String(l)]}else r[a]=l}return{positional:e,flags:r}}function Jn(t,e){let r=t[e];if(typeof r=="string"&&r.length>0)return r}function SR(t,e){return t[e]===!0||t[e]==="true"}function kR(t,e){let r=t[e];if(Array.isArray(r))return r.filter(Boolean);if(typeof r=="string"&&r.length>0)return[r]}function tb(t,e,r={}){let n=Jn(t,e);if(!n)return;let o=Number(n),s=r.min??1;if(!Number.isInteger(o)||o<s)throw new Error(`--${e} must be an integer >= ${s}`);return o}function QZ(t){let e=Jn(t,"ext")??Jn(t,"extensions");if(!e)return;let r=e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.startsWith(".")?n:`.${n}`);return r.length>0?r:void 0}function RR(t,e){return t?Q(t):Q(e)}async function CR(t){let e=await bs(vt().platform),r=vn(()=>e.getSessionDir()),n=Ir(r),{resolveContentStorePath:o}=await Promise.resolve().then(()=>(Jt(),Xb)),s=o({projectDir:t,contentDir:n});return{store:new vs(s),dbPath:s,contentDir:n}}function eq(t){try{if(ER(t).isDirectory())return`project:${zZ(t)||t}`}catch{}return t}function tq(t,e){let r=lo("Read",e);if(po(t,r,process.platform==="win32",e).denied)throw new Error(`Read denied by policy: ${t}`)}async function rq(t){try{let e=PR(t),r=e.positional[0];if(!r||r==="-h"||r==="--help")return console.log("Usage: context-mode index <path> [--source label] [--project path] [--max-files n] [--max-depth n] [--ext .ts,.md]"),r?0:1;let n=FZ(r)?Q(r):Q(process.cwd(),r);if(!$e(n))throw new Error(`Path does not exist: ${n}`);let o=ER(n),s=RR(Jn(e.flags,"project"),o.isDirectory()?n:rb(n)),i=Jn(e.flags,"source")??eq(n),{store:a,dbPath:c}=await CR(s);try{if(tq(n,s),o.isDirectory()){let u=lo("Read",s),l=a.indexDirectory({path:n,source:i,include:kR(e.flags,"include"),exclude:kR(e.flags,"exclude"),maxDepth:tb(e.flags,"max-depth",{min:0}),maxFiles:tb(e.flags,"max-files"),extensions:QZ(e.flags),respectGitignore:!SR(e.flags,"no-gitignore"),followSymlinks:SR(e.flags,"follow-symlinks"),perFileDeny:p=>{try{return po(p,u,process.platform==="win32",s).denied}catch{return!1}}}),d=l.capped?` (cap reached at ${l.filesIndexed} files)`:"",m=l.denied>0?`; ${l.denied} denied`:"",h=l.failed>0?`; ${l.failed} failed`:"";console.log(`Indexed ${l.filesIndexed} files (${l.totalChunks} sections) from ${n}${d}${m}${h}`)}else{let u=a.index({path:n,source:i});console.log(`Indexed ${u.totalChunks} sections (${u.codeChunks} with code) from ${n}`)}return console.log(`Source: ${i}`),console.log(`Project: ${s}`),console.log(`DB: ${c}`),0}finally{a.close()}}catch(e){let r=e instanceof Error?e.message:String(e);return console.error(`context-mode index: ${r}`),1}}async function nq(t){try{let e=PR(t),r=e.positional.join(" ").trim();if(!r||r==="-h"||r==="--help")return console.log("Usage: context-mode search <query...> [--source label] [--project path] [--limit n] [--type code|prose]"),r?0:1;let n=RR(Jn(e.flags,"project"),process.cwd()),{store:o,dbPath:s}=await CR(n);try{let i=tb(e.flags,"limit")??3,a=Jn(e.flags,"type");if(a&&a!=="code"&&a!=="prose")throw new Error("--type must be code or prose");let c=o.searchWithFallback(r,i,Jn(e.flags,"source"),a);if(c.length===0)return console.log(`No matches for: ${r}`),console.log(`Project: ${n}`),console.log(`DB: ${s}`),0;for(let[u,l]of c.entries()){let d=l.content.replace(/\s+/g," ").trim(),m=d.length>500?`${d.slice(0,500)}...`:d;console.log(`## ${u+1}. ${l.title}`),console.log(`Source: ${l.source}`),console.log(`Type: ${l.contentType}`),console.log(m),console.log("")}return 0}finally{o.close()}}catch(e){let r=e instanceof Error?e.message:String(e);return console.error(`context-mode search: ${r}`),1}}function eb(t){try{return Ir(t),I.success(w.default.green(`Storage ${t.kind}: PASS`)+w.default.dim(` \u2014 ${t.path} (${ld(t)})`)),0}catch(e){if(e instanceof Kt)return I.error(w.default.red(`Storage ${t.kind}: FAIL`)+w.default.dim(` \u2014 ${is(e)}`)),1;throw e}}async function oq(){process.stdout.isTTY&&console.clear();let t=vt(),e=await bs(t.platform);Pd(w.default.bgMagenta(w.default.white(" context-mode doctor "))),I.info(`Platform: ${w.default.cyan(e.name)}`+w.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0;try{let y=Jr(()=>e.getSessionDir()),_=vn(()=>y.path),b=ss(()=>y.path);mc([`sessions: ${y.path} (${ld(y)})`,`content: ${_.path} (${ld(_)})`,`stats: ${b.path} (${ld(b)})`].join(`
1157
+ `),"Storage paths"),r+=eb(y),r+=eb(_),r+=eb(b)}catch(y){if(y instanceof Kt)r++,I.error(w.default.red(`Storage ${y.kind}: FAIL`)+w.default.dim(` \u2014 ${is(y)}`));else throw y}let n=Rd();n.start("Running diagnostics");let o,s;try{o=Yn(),s=Ei(o)}catch{return n.stop("Diagnostics partial"),I.warn(w.default.yellow("Could not detect runtimes")+w.default.dim(" \u2014 module may be missing, restart session after upgrade")),pc(w.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),mc(wi(o),"Runtimes");{let{hasModernSqlite:y}=await Promise.resolve().then(()=>(bn(),Hd));process.platform==="linux"&&!y()&&!yn()&&(r++,I.error(w.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+w.default.dim(`
1107
1158
  context-mode requires Node.js >= 22.5 (or Bun) on Linux to avoid the
1108
1159
  V8 madvise(MADV_DONTNEED) SIGSEGV in better-sqlite3 (1-4/hour).
1109
1160
  Refs: https://github.com/nodejs/node/issues/62515
1110
1161
  https://github.com/mksglu/context-mode/issues/564
1111
1162
  Fix: nvm install 22.5 && nvm use 22.5 && npm install -g context-mode
1112
- Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}Bn()?C.success(k.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):C.warn(k.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(s.length/i*100).toFixed(0);s.length<2?(r++,C.error(k.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+k.default.dim(` \u2014 ${s.join(", ")||"none"}`))):C.info(`Language coverage: ${s.length}/${i} (${a}%)`+k.default.dim(` \u2014 ${s.join(", ")}`)),C.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(Zy(),$$)),_=await new y({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(_.exitCode===0&&_.stdout.trim()==="ok")C.success(k.default.green("Server test: PASS"));else{r++;let b=_.stderr?.trim()?` (${_.stderr.trim().slice(0,200)})`:"";C.error(k.default.red("Server test: FAIL")+` \u2014 exit ${_.exitCode}${b}`)}}catch(y){let v=y instanceof Error?y.message:String(y);v.includes("Cannot find module")||v.includes("MODULE_NOT_FOUND")?C.warn(k.default.yellow("Server test: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,C.error(k.default.red("Server test: FAIL")+` \u2014 ${v}`))}C.step(`Checking ${e.name} hooks configuration...`);let c=jo(),u=e.validateHooks(c);for(let y of u)y.status==="pass"?C.success(k.default.green(`${y.check}: PASS`)+` \u2014 ${y.message}`):y.status==="warn"?C.warn(k.default.yellow(`${y.check}: WARN`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
1113
- Run: ${y.fix}`):"")):C.error(k.default.red(`${y.check}: FAIL`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
1114
- Run: ${y.fix}`):""));C.step("Checking hook scripts...");let d=e.getHealthChecks?.(c)??[];if(d.length>0)for(let y of d){let v=y.check();v.status==="OK"?C.success(k.default.green(`${y.name}: PASS`)+(v.detail?k.default.dim(` \u2014 ${v.detail}`):"")):C.error(k.default.red(`${y.name}: FAIL`)+(v.detail?k.default.dim(` \u2014 ${v.detail}`):""))}else{let y=tc(e,c);if(y.length===0)C.success(k.default.green("Hook scripts: PASS")+k.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let v of y){let _=ae(c,v);try{_P(_,vP.R_OK),C.success(k.default.green("Hook script exists: PASS")+k.default.dim(` \u2014 ${_}`))}catch{C.error(k.default.red("Hook script exists: FAIL")+k.default.dim(` \u2014 not found at ${_}`))}}}C.step(`Checking ${e.name} plugin registration...`);let l=e.checkPluginRegistration();l.status==="pass"?C.success(k.default.green("Plugin enabled: PASS")+k.default.dim(` \u2014 ${l.message}`)):C.warn(k.default.yellow("Plugin enabled: WARN")+` \u2014 ${l.message}`),C.step("Checking team-shared hook configs in your workspace...");{let x=function(E){return!!(E.startsWith("/")||/^[A-Za-z]:[/\\]/.test(E)||E.includes("\\\\")||E.includes("fnm_multishells")||E.includes("process.execPath"))},P=function(E,R){if(typeof E=="string")R(E);else if(Array.isArray(E))for(let A of E)P(A,R);else if(E&&typeof E=="object")for(let A of Object.values(E))P(A,R)};var h=x,g=P;let y=process.cwd(),v=[".github/hooks/context-mode.json",".cursor/hooks.json",".jetbrains/copilot/hooks.json"],_=0,b=0;for(let E of v){let R=ae(y,E);if(Ie(R)){b++;try{let A=JSON.parse(Lr(R,"utf-8")),L=[];if(P(A,w=>{x(w)&&L.push(w)}),L.length>0){r++,_++;let w=L[0].length>100?L[0].slice(0,97)+"...":L[0];C.error(k.default.red("Hook config: FAIL")+` \u2014 ${E} has your machine's local paths baked in`+k.default.dim(`
1163
+ Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}yn()?I.success(w.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):I.warn(w.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(s.length/i*100).toFixed(0);s.length<2?(r++,I.error(w.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+w.default.dim(` \u2014 ${s.join(", ")||"none"}`))):I.info(`Language coverage: ${s.length}/${i} (${a}%)`+w.default.dim(` \u2014 ${s.join(", ")}`)),I.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(S_(),NT)),b=await new y({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(b.exitCode===0&&b.stdout.trim()==="ok")I.success(w.default.green("Server test: PASS"));else{r++;let v=b.stderr?.trim()?` (${b.stderr.trim().slice(0,200)})`:"";I.error(w.default.red("Server test: FAIL")+` \u2014 exit ${b.exitCode}${v}`)}}catch(y){let _=y instanceof Error?y.message:String(y);_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?I.warn(w.default.yellow("Server test: SKIP")+w.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,I.error(w.default.red("Server test: FAIL")+` \u2014 ${_}`))}I.step(`Checking ${e.name} hooks configuration...`);let c=Go(),u=e.validateHooks(c);for(let y of u)y.status==="pass"?I.success(w.default.green(`${y.check}: PASS`)+` \u2014 ${y.message}`):y.status==="warn"?I.warn(w.default.yellow(`${y.check}: WARN`)+` \u2014 ${y.message}`+(y.fix?w.default.dim(`
1164
+ Run: ${y.fix}`):"")):I.error(w.default.red(`${y.check}: FAIL`)+` \u2014 ${y.message}`+(y.fix?w.default.dim(`
1165
+ Run: ${y.fix}`):""));I.step("Checking hook scripts...");let l=e.getHealthChecks?.(c)??[];if(l.length>0)for(let y of l){let _=y.check();_.status==="OK"?I.success(w.default.green(`${y.name}: PASS`)+(_.detail?w.default.dim(` \u2014 ${_.detail}`):"")):I.error(w.default.red(`${y.name}: FAIL`)+(_.detail?w.default.dim(` \u2014 ${_.detail}`):""))}else{let y=_c(e,c);if(y.length===0)I.success(w.default.green("Hook scripts: PASS")+w.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let _ of y){let b=Q(c,_);try{wR(b,$R.R_OK),I.success(w.default.green("Hook script exists: PASS")+w.default.dim(` \u2014 ${b}`))}catch{I.error(w.default.red("Hook script exists: FAIL")+w.default.dim(` \u2014 not found at ${b}`))}}}I.step(`Checking ${e.name} plugin registration...`);let d=e.checkPluginRegistration();d.status==="pass"?I.success(w.default.green("Plugin enabled: PASS")+w.default.dim(` \u2014 ${d.message}`)):I.warn(w.default.yellow("Plugin enabled: WARN")+` \u2014 ${d.message}`),I.step("Checking team-shared hook configs in your workspace...");{let E=function(x){return!!(x.startsWith("/")||/^[A-Za-z]:[/\\]/.test(x)||x.includes("\\\\")||x.includes("fnm_multishells")||x.includes("process.execPath"))},C=function(x,k){if(typeof x=="string")k(x);else if(Array.isArray(x))for(let P of x)C(P,k);else if(x&&typeof x=="object")for(let P of Object.values(x))C(P,k)};var f=E,g=C;let y=process.cwd(),_=[".github/hooks/context-mode.json",".cursor/hooks.json",".jetbrains/copilot/hooks.json"],b=0,v=0;for(let x of _){let k=Q(y,x);if($e(k)){v++;try{let P=JSON.parse(Wr(k,"utf-8")),N=[];if(C(P,R=>{E(R)&&N.push(R)}),N.length>0){r++,b++;let R=N[0].length>100?N[0].slice(0,97)+"...":N[0];I.error(w.default.red("Hook config: FAIL")+` \u2014 ${x} has your machine's local paths baked in`+w.default.dim(`
1115
1166
  This file is committed to git, so teammates and CI will get your path and the hooks will break for them.
1116
- Found ${L.length} hard-coded path(s), e.g.: ${w}
1167
+ Found ${N.length} hard-coded path(s), e.g.: ${R}
1117
1168
  Fix: run /context-mode:ctx-upgrade \u2014 it rewrites the file to a portable form that works on every machine.
1118
- Details: https://github.com/mksglu/context-mode/issues/613`))}else C.success(k.default.green("Hook config: PASS")+k.default.dim(` \u2014 ${E} is portable (no hard-coded paths)`))}catch(A){let L=A instanceof Error?A.message:String(A);C.warn(k.default.yellow("Hook config: WARN")+` \u2014 ${E} is not valid JSON`+k.default.dim(`
1169
+ Details: https://github.com/mksglu/context-mode/issues/613`))}else I.success(w.default.green("Hook config: PASS")+w.default.dim(` \u2014 ${x} is portable (no hard-coded paths)`))}catch(P){let N=P instanceof Error?P.message:String(P);I.warn(w.default.yellow("Hook config: WARN")+` \u2014 ${x} is not valid JSON`+w.default.dim(`
1119
1170
  Doctor cannot scan it for portability issues until the file parses.
1120
1171
  Fix: open the file and check it in a JSON validator, or delete it and run /context-mode:ctx-upgrade to regenerate.
1121
- Parser said: ${L.slice(0,160)}`))}}}b===0&&C.info(k.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}C.step("Checking for leftover .mcp.json files from older versions...");{let y=mt(Kl(),".claude","plugins","cache","context-mode","context-mode");if(!Ie(y))C.info(k.default.dim("Leftover .mcp.json check: SKIP \u2014 no plugin cache exists yet (Claude Code has not installed context-mode here)"));else{let v=0,_=[];try{let b=rZ(y);for(let x of b){let P=mt(y,x,".mcp.json");Ie(P)&&(v++,_.length<5&&_.push(x))}}catch(b){let x=b instanceof Error?b.message:String(b);C.warn(k.default.yellow("Leftover .mcp.json check: WARN")+" \u2014 could not read the plugin cache directory"+k.default.dim(`
1172
+ Parser said: ${N.slice(0,160)}`))}}}v===0&&I.info(w.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}I.step("Checking for leftover .mcp.json files from older versions...");{let y=yt(pd(),".claude","plugins","cache","context-mode","context-mode");if(!$e(y))I.info(w.default.dim("Leftover .mcp.json check: SKIP \u2014 no plugin cache exists yet (Claude Code has not installed context-mode here)"));else{let _=0,b=[];try{let v=AZ(y);for(let E of v){let C=yt(y,E,".mcp.json");$e(C)&&(_++,b.length<5&&b.push(E))}}catch(v){let E=v instanceof Error?v.message:String(v);I.warn(w.default.yellow("Leftover .mcp.json check: WARN")+" \u2014 could not read the plugin cache directory"+w.default.dim(`
1122
1173
  Path: ${y}
1123
- Reason: ${x.slice(0,160)}
1124
- Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),v=0}v===0?C.success(k.default.green("Leftover .mcp.json check: PASS")+k.default.dim(" \u2014 no old .mcp.json files in the plugin cache")):C.warn(k.default.yellow("Leftover .mcp.json check: WARN")+` \u2014 found ${v} old .mcp.json file(s) left over from previous context-mode versions`+k.default.dim(`
1174
+ Reason: ${E.slice(0,160)}
1175
+ Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),_=0}_===0?I.success(w.default.green("Leftover .mcp.json check: PASS")+w.default.dim(" \u2014 no old .mcp.json files in the plugin cache")):I.warn(w.default.yellow("Leftover .mcp.json check: WARN")+` \u2014 found ${_} old .mcp.json file(s) left over from previous context-mode versions`+w.default.dim(`
1125
1176
  These are harmless but should be cleaned up so they cannot confuse Claude Code after an auto-update.
1126
- Versions affected: ${_.join(", ")}${v>_.length?", ...":""}
1177
+ Versions affected: ${b.join(", ")}${_>b.length?", ...":""}
1127
1178
  Fix: run /context-mode:ctx-upgrade \u2014 it sweeps these files automatically on the next run.
1128
- Details: https://github.com/mksglu/context-mode/issues/609`))}}C.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(ln(),vd))).loadDatabase(),v=new y(":memory:");v.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),v.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let _=v.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();v.close(),_&&_.content==="hello world"?C.success(k.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,C.error(k.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(y){let v=y instanceof Error?y.message:String(y),_=jo(),b=ae(_,"node_modules","better-sqlite3");!Ie(b)?(r++,C.error(k.default.red("FTS5 / better-sqlite3: FAIL")+k.default.dim(" \u2014 package-missing")+k.default.dim(`
1129
- Path: ${b}
1179
+ Details: https://github.com/mksglu/context-mode/issues/609`))}}I.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(bn(),Hd))).loadDatabase(),_=new y(":memory:");_.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),_.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let b=_.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();_.close(),b&&b.content==="hello world"?I.success(w.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,I.error(w.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(y){let _=y instanceof Error?y.message:String(y),b=Go(),v=Q(b,"node_modules","better-sqlite3");!$e(v)?(r++,I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+w.default.dim(" \u2014 package-missing")+w.default.dim(`
1180
+ Path: ${v}
1130
1181
  Root cause: npm silently skipped better-sqlite3 because the package's \`engines\` field excluded the running Node (issue #514, e.g. Node 26 vs better-sqlite3@12.x).
1131
- Try (primary): cd "${_}" && npm install better-sqlite3 --no-optional
1132
- Try (fallback): /context-mode:ctx-upgrade`))):v.includes("Cannot find module")||v.includes("MODULE_NOT_FOUND")?C.warn(k.default.yellow("FTS5 / better-sqlite3: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,(/Could not locate the bindings file/i.test(v)||/bindings\.node/i.test(v)||/\bbindings\b/i.test(v))&&process.platform==="win32"?C.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${v}`+k.default.dim(`
1182
+ Try (primary): cd "${b}" && npm install better-sqlite3 --no-optional
1183
+ Try (fallback): /context-mode:ctx-upgrade`))):_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?I.warn(w.default.yellow("FTS5 / better-sqlite3: SKIP")+w.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,(/Could not locate the bindings file/i.test(_)||/bindings\.node/i.test(_)||/\bbindings\b/i.test(_))&&process.platform==="win32"?I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+w.default.dim(`
1133
1184
  Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
1134
1185
  Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
1135
- Try (fallback): npm rebuild better-sqlite3`)):C.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${v}`+k.default.dim(`
1136
- Try: npm rebuild better-sqlite3`)))}C.step("Checking versions...");let m=SP(),f=await vZ(),p=e.getInstalledVersion();return f==="unknown"?C.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, could not reach npm registry`):m===f?C.success(k.default.green("npm (MCP): PASS")+` \u2014 v${m}`):C.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, latest v${f}`+k.default.dim(`
1137
- Run: /context-mode:ctx-upgrade`)),p==="standalone"?C.info(k.default.dim(`${e.name}: standalone MCP mode`)+" \u2014 no platform plugin version to compare"):p==="not installed"?C.info(k.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):f!=="unknown"&&p===f?C.success(k.default.green(`${e.name}: PASS`)+` \u2014 v${p}`):f!=="unknown"?C.warn(k.default.yellow(`${e.name}: WARN`)+` \u2014 v${p}, latest v${f}`+k.default.dim(`
1138
- Run: /context-mode:ctx-upgrade`)):C.info(`${e.name}: v${p}`+k.default.dim(" \u2014 could not verify against npm registry")),r>0?(Va(k.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(Va(s.length>=4?k.default.green("Diagnostics complete!"):k.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function xZ(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:o,cpSync:s}=await import("node:fs"),i=ae(jo(),"insight"),a=Et(),c=await _i(a.platform),u=mn(pn(()=>c.getSessionDir())),d=mn(qo(()=>u)),l=mt(bP(u),"insight-cache");Ie(mt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),o(l,{recursive:!0});let m=n(mt(i,"server.mjs")).mtimeMs,f=Ie(mt(l,"server.mjs"))?n(mt(l,"server.mjs")).mtimeMs:0;if(m>f&&(console.log("Copying Insight source..."),s(i,l,{recursive:!0,force:!0})),!Ie(mt(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{hZ("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{Qs(mt(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!Ie(mt(l,"node_modules","vite"))||!Ie(mt(l,"node_modules","better-sqlite3")))throw Qs(mt(l,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:l,stdio:"pipe",timeout:6e4});let p=`http://localhost:${t}`;console.log(`
1186
+ Try (fallback): npm rebuild better-sqlite3`)):I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+w.default.dim(`
1187
+ Try: npm rebuild better-sqlite3`)))}I.step("Checking versions...");let m=TR(),h=await YZ(),p=e.getInstalledVersion();return h==="unknown"?I.warn(w.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, could not reach npm registry`):m===h?I.success(w.default.green("npm (MCP): PASS")+` \u2014 v${m}`):I.warn(w.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, latest v${h}`+w.default.dim(`
1188
+ Run: /context-mode:ctx-upgrade`)),p==="standalone"?I.info(w.default.dim(`${e.name}: standalone MCP mode`)+" \u2014 no platform plugin version to compare"):p==="not installed"?I.info(w.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):h!=="unknown"&&p===h?I.success(w.default.green(`${e.name}: PASS`)+` \u2014 v${p}`):h!=="unknown"?I.warn(w.default.yellow(`${e.name}: WARN`)+` \u2014 v${p}, latest v${h}`+w.default.dim(`
1189
+ Run: /context-mode:ctx-upgrade`)):I.info(`${e.name}: v${p}`+w.default.dim(" \u2014 could not verify against npm registry")),r>0?(pc(w.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(pc(s.length>=4?w.default.green("Diagnostics complete!"):w.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function sq(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:o,cpSync:s}=await import("node:fs"),i=Q(Go(),"insight"),a=vt(),c=await bs(a.platform),u=Ir(Jr(()=>c.getSessionDir())),l=Ir(vn(()=>u)),d=yt(rb(u),"insight-cache");$e(yt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),o(d,{recursive:!0});let m=n(yt(i,"server.mjs")).mtimeMs,h=$e(yt(d,"server.mjs"))?n(yt(d,"server.mjs")).mtimeMs:0;if(m>h&&(console.log("Copying Insight source..."),s(i,d,{recursive:!0,force:!0})),!$e(yt(d,"node_modules"))){console.log("Installing dependencies (first run)...");try{KZ("npm install --production=false",{cwd:d,stdio:"inherit",timeout:3e5})}catch{try{_i(yt(d,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!$e(yt(d,"node_modules","vite"))||!$e(yt(d,"node_modules","better-sqlite3")))throw _i(yt(d,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:d,stdio:"pipe",timeout:6e4});let p=`http://localhost:${t}`;console.log(`
1139
1190
  context-mode Insight
1140
1191
  ${p}
1141
- `);let h=r("node",[mt(l,"server.mjs")],{cwd:l,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:d},stdio:"inherit"});h.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,v)=>{let _=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},b=>{y(),b.resume()});_.on("error",v),_.on("timeout",()=>{_.destroy(),v(new Error("timeout"))}),_.end()})}catch{console.error(`
1192
+ `);let f=r("node",[yt(d,"server.mjs")],{cwd:d,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:l},stdio:"inherit"});f.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,_)=>{let b=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},v=>{y(),v.resume()});b.on("error",_),b.on("timeout",()=>{b.destroy(),_(new Error("timeout"))}),b.end()})}catch{console.error(`
1142
1193
  Error: Port ${t} appears to be in use. Either a previous dashboard is still running, or another service is using this port.`),console.error(`
1143
- To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}gZ(p),process.on("SIGINT",()=>{h.kill(),process.exit(0)}),process.on("SIGTERM",()=>{h.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
1144
- Insight error: ${r}`),process.exit(1)}}async function SZ(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:Et(),r=await _i(e.platform);dd(k.default.bgCyan(k.default.black(" context-mode upgrade "))),C.info(`Platform: ${k.default.cyan(r.name)}`+k.default.dim(` (${e.confidence} confidence)`));let n=jo(),o=[],s=pd(),i=ae(qe(),"plugins","marketplaces","context-mode");if(Ie(mt(i,".git"))){s.start("Syncing marketplace clone");try{Xs("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(k.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),C.info(k.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):(Xs("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),Xs("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(k.default.green("Marketplace clone synced")),o.push("Marketplace clone updated to upstream"))}catch(m){let f=m instanceof Error?m.message:String(m);s.stop(k.default.yellow("Marketplace sync skipped")),C.warn(k.default.yellow("git refresh on marketplace failed")+` \u2014 ${f}`),C.info(k.default.dim(" Continuing \u2014 cache dir update will still happen."))}}C.step("Pulling latest from GitHub...");let a=SP(),c=mt(aZ(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{Xs("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let m=c,p=JSON.parse(Lr(ae(m,"package.json"),"utf-8")).version??"unknown";if(p===a)C.success(k.default.green("Already on latest")+` \u2014 v${a}`),Qs(c,{recursive:!0,force:!0});else{C.info(`Update available: ${k.default.yellow("v"+a)} \u2192 ${k.default.green("v"+p)}`);try{let b=zb({ownPid:process.pid,ownPpid:process.ppid});if(b.length>0){let x=await Lb({pids:b});if(x.totalKilled>0){let P=x.totalKilled===1?"sibling MCP server":"sibling MCP servers";C.info(k.default.dim(`Stopped ${x.totalKilled} ${P} (SIGTERM: ${x.terminatedBySigterm}, SIGKILL: ${x.terminatedBySigkill})`))}}}catch{}s.start("Installing dependencies & building");let h=Hb();Wl(["install","--no-audit","--no-fund"],{cwd:m,stdio:"pipe",timeout:12e4,...h?{env:{...process.env,npm_config_msvs_version:h}}:{}}),Wl(["run","build"],{cwd:m,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let y=[...JSON.parse(Lr(ae(m,"package.json"),"utf-8")).files||[],"src","package.json"];for(let b of y)try{Qs(ae(n,b),{recursive:!0,force:!0}),yP(ae(m,b),ae(n,b),{recursive:!0})}catch{}try{(await Promise.resolve().then(()=>(gP(),hP))).normalizeHooksOnStartup({pluginRoot:n,nodePath:process.execPath,platform:process.platform})}catch{}s.stop(k.default.green(`Updated in-place to v${p}`));let v=ae(n,".claude-plugin","plugin.json"),_=null;try{let b=JSON.parse(Lr(v,"utf-8"));b&&typeof b.version=="string"&&(_=b.version)}catch{}if(_!==p)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${_??"<missing>"}" but newVersion is "${p}". Refusing to bump registry.`);r.updatePluginRegistry(n,p),C.info(k.default.dim(" Registry synced to "+n));try{let b=ae(qe(),"plugins","installed_plugins.json");if(Ie(b)){let P=JSON.parse(Lr(b,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let E of P){let R=E?.installPath;if(typeof R!="string"||!R)continue;if(!Ie(R))throw new Error(`installPath does not exist on disk: ${R}`);let A=ae(R,".claude-plugin","plugin.json");if(!Ie(A))throw new Error(`missing plugin.json manifest at ${A}`);let L=JSON.parse(Lr(A,"utf-8"));if(L?.version!==E.version)throw new Error(`version mismatch \u2014 registry says "${E.version}" but ${A} says "${L?.version}"`)}}}catch(b){let x=b instanceof Error?b.message:String(b);throw new Error(`Registry consistency check failed: ${x}`)}try{let b=ae(qe(),"plugins","cache"),x="context-mode@context-mode",P=xc({pluginRoot:n,pluginCacheRoot:b,pluginKey:x});if(P&&P.error)throw new Error(P.error);let E=xc({pluginRoot:n,pluginCacheRoot:b,pluginKey:x});if(E&&Array.isArray(E.healed)&&E.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${E.healed.join(",")})`)}catch(b){let x=b instanceof Error?b.message:String(b);throw new Error(`plugin.json drift check failed: ${x}`)}try{let b=ae(qe(),"plugins","cache"),x="context-mode@context-mode",P=Sc({pluginCacheRoot:b,pluginKey:x});P&&P.removed&&P.removed.length>0&&C.info(k.default.dim(` Swept ${P.removed.length} stale .mcp.json file(s) from cache`));let E=Sc({pluginCacheRoot:b,pluginKey:x});if(E&&Array.isArray(E.removed)&&E.removed.length>0)throw new Error(`.mcp.json sweep drift: ${E.removed.length} file(s) still present after first pass`)}catch(b){let x=b instanceof Error?b.message:String(b);throw new Error(`.mcp.json sweep check failed: ${x}`)}try{let{healClaudeJsonMcpArgs:b}=await Promise.resolve().then(()=>(bp(),Ub)),x=ae(Kl(),".claude.json"),P=ae(qe(),"plugins","cache","context-mode","context-mode"),E=b({dotClaudeJsonPath:x,pluginCacheParent:P,newPluginRoot:n});E.healed&&E.healed.length>0&&C.info(k.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+p))}catch{}try{let b=ae(i,".claude-plugin","plugin.json");if(Ie(b)){let x=JSON.parse(Lr(b,"utf-8"));x?.version!==p&&(C.warn(k.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${x?.version}" but expected "${p}"`),C.info(k.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(s.start("Installing production dependencies"),Wl(["install","--production","--no-audit","--no-fund"],{cwd:n,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),!xP(e.platform)){s.start("Verifying native addon ABI");let b=ae(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let P=ae(n,"hooks","ensure-deps.mjs");if(!Ie(P))throw new Error(`missing ${P}`);await import(`${Jl(P).href}?upgrade=${Date.now()}`),Ie(b)?(s.stop(k.default.green("Native addons OK")+k.default.dim(" \u2014 ABI cache present")),o.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(k.default.yellow("Native addon ABI cache missing")),C.warn(k.default.dim(` Try manually: cd "${n}" && npm rebuild better-sqlite3`)))}catch(P){let E=P instanceof Error?P.message:String(P);s.stop(k.default.yellow("Native addon ABI bootstrap unavailable")),C.warn(k.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${E}`+k.default.dim(`
1145
- Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let x=ae(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Ie(x))try{let P=ae(n,"scripts","heal-better-sqlite3.mjs");if(Ie(P)){let E=await import(`${Jl(P).href}?upgrade=${Date.now()}`);typeof E.healBetterSqlite3Binding=="function"&&E.healBetterSqlite3Binding(n)}}catch{}Ie(x)||(process.exitCode=1,C.error(k.default.red("better-sqlite3 native binding: MISSING")+k.default.dim(`
1146
- Path: ${x}`)+k.default.dim(`
1147
- Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+k.default.dim(`
1148
- Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+k.default.dim(`
1149
- Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{Wl(["install","-g",n,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(k.default.green("npm global updated")),o.push("Updated npm global package")}catch{s.stop(k.default.yellow("npm global update skipped")),C.info(k.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}Qs(c,{recursive:!0,force:!0});try{let b=ae(qe(),"plugins","installed_plugins.json");if(Ie(b)){let P=JSON.parse(Lr(b,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let E of P){let R=E.installPath;if(R&&R!==n&&Ie(R)){let A=ae(m,"skills");Ie(A)&&(yP(A,ae(R,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}}catch{}o.push(`Updated v${a} \u2192 v${p}`),C.success(k.default.green("Plugin reinstalled from GitHub!")+k.default.dim(` \u2014 v${p}`))}}catch(m){let f=m instanceof Error?m.message:String(m);s.stop(k.default.red("Update failed")),C.error(k.default.red("GitHub pull failed")+` \u2014 ${f}`),process.exitCode=1,C.warn(k.default.yellow("In-place files were NOT updated")+k.default.dim(" \u2014 old version is still on disk; hooks/settings will still be refreshed.")),C.info(k.default.dim(" Recovery: re-run /ctx-upgrade once network is stable, or run /context-mode:ctx-doctor for a full health check."));try{Qs(c,{recursive:!0,force:!0})}catch{}}C.step(`Backing up ${r.name} settings...`);let u=r.backupSettings();u?.endsWith(".bak")?(C.success(k.default.green("Backup created")+k.default.dim(" -> "+u)),o.push("Backed up settings")):u?C.success(k.default.green("Backup skipped")+k.default.dim(" \u2014 no changes needed")):C.warn(k.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),C.step(`Configuring ${r.name} hooks...`);try{let m=r.configureAllHooks(n);for(let f of m)C.info(k.default.dim(` ${f}`)),o.push(f);C.success(k.default.green("Hooks configured")+k.default.dim(` \u2014 ${r.name}`))}catch(m){let f=m instanceof Error?m.message:String(m);throw new Error(`Hook configuration failed: ${f}`)}C.step("Setting hook script permissions...");let d=r.setHookPermissions(n);if(process.platform!=="win32")for(let m of["build/cli.js","cli.bundle.mjs"]){let f=ae(n,m);try{_P(f,vP.F_OK),sZ(f,493),d.push(f)}catch{}}d.length>0?(C.success(k.default.green("Permissions set")+k.default.dim(` \u2014 ${d.length} hook script(s)`)),o.push(`Set ${d.length} hook scripts as executable`)):C.error(k.default.red("No hook scripts found")+k.default.dim(" \u2014 expected in "+ae(n,"hooks"))),o.length>0?Wa(o.map(m=>k.default.green(" + ")+m).join(`
1150
- `),"Changes Applied"):C.info(k.default.dim("No changes were needed."));let l=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";C.warn(k.default.yellow("Restart for new MCP tools to take effect.")+k.default.dim(` (${l})`)),C.step("Running doctor to verify..."),console.log();try{let m=ae(n,"cli.bundle.mjs"),f=ae(n,"build","cli.js"),p=Ie(m)?m:f;Xs("node",[p,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{C.warn(k.default.yellow("Doctor had warnings")+k.default.dim(` \u2014 restart your ${r.name} session to pick up the new version`))}}function kZ(){let t=qe(),e=[ae(jo(),"bin","statusline.mjs"),ae(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=ae(t,"plugins","installed_plugins.json");if(Ie(n)){let s=JSON.parse(Lr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(s))for(let i of s){let a=i?.installPath;typeof a=="string"&&a&&e.push(ae(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>Ie(n));r||process.exit(0),import(Jl(r).href).catch(()=>{process.exit(0)})}export{hZ as npmExec,Wl as npmExecFile,gZ as openInBrowser,m8 as toUnixPath};
1194
+ To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),f.kill(),process.exit(1)}GZ(p),process.on("SIGINT",()=>{f.kill(),process.exit(0)}),process.on("SIGTERM",()=>{f.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
1195
+ Insight error: ${r}`),process.exit(1)}}async function iq(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:vt(),r=await bs(e.platform);Pd(w.default.bgCyan(w.default.black(" context-mode upgrade "))),I.info(`Platform: ${w.default.cyan(r.name)}`+w.default.dim(` (${e.confidence} confidence)`));let n=Go(),o=[],s=Rd(),i=Q(qe(),"plugins","marketplaces","context-mode");if($e(yt(i,".git"))){s.start("Syncing marketplace clone");try{yi("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(w.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),I.info(w.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):(yi("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),yi("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(w.default.green("Marketplace clone synced")),o.push("Marketplace clone updated to upstream"))}catch(m){let h=m instanceof Error?m.message:String(m);s.stop(w.default.yellow("Marketplace sync skipped")),I.warn(w.default.yellow("git refresh on marketplace failed")+` \u2014 ${h}`),I.info(w.default.dim(" Continuing \u2014 cache dir update will still happen."))}}I.step("Pulling latest from GitHub...");let a=TR(),c=yt(HZ(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{yi("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let m=c,p=JSON.parse(Wr(Q(m,"package.json"),"utf-8")).version??"unknown";if(p===a)I.success(w.default.green("Already on latest")+` \u2014 v${a}`),_i(c,{recursive:!0,force:!0});else{I.info(`Update available: ${w.default.yellow("v"+a)} \u2192 ${w.default.green("v"+p)}`);try{let x=Wv({ownPid:process.pid,ownPpid:process.ppid});if(x.length>0){let k=await Kv({pids:x});if(k.totalKilled>0){let P=k.totalKilled===1?"sibling MCP server":"sibling MCP servers";I.info(w.default.dim(`Stopped ${k.totalKilled} ${P} (SIGTERM: ${k.terminatedBySigterm}, SIGKILL: ${k.terminatedBySigkill})`))}}}catch{}s.start("Installing dependencies & building");let f=Jv();ud(["install","--no-audit","--no-fund"],{cwd:m,stdio:"pipe",timeout:12e4,...f?{env:{...process.env,npm_config_msvs_version:f}}:{}}),ud(["run","build"],{cwd:m,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let y=[...JSON.parse(Wr(Q(m,"package.json"),"utf-8")).files||[],"src","package.json"],_=Q(n)+Kr,b=Q(m)+Kr,v=x=>{try{return!jZ(x).isSymbolicLink()}catch{return!1}};for(let x of y){let k=Q(m,x),P=Q(n,x);if((P+Kr).startsWith(_)&&(k+Kr).startsWith(b)&&v(k)&&$e(k))try{_i(P,{recursive:!0,force:!0}),vR(k,P,{recursive:!0,filter:v})}catch{}}try{let x;try{let{resolveHookRuntime:P}=await Promise.resolve().then(()=>(Xo(),Ob)),N=P();N.isBun&&(x=N.path)}catch{}(await Promise.resolve().then(()=>(dR(),lR))).normalizeHooksJsonOnly({pluginRoot:n,nodePath:process.execPath,jsRuntimePath:x,platform:process.platform})}catch{}try{if(e.platform==="claude-code"){let{rewriteShellSnapshots:x}=await Promise.resolve().then(()=>(xR(),bR)),k=Q(qe(),"shell-snapshots"),P=x({snapshotsDir:k,currentVersion:p});P.rewritten.length>0&&I.info(w.default.dim(` Healed ${P.rewritten.length} stale shell snapshot(s) \u2014 Bash tool calls in the active session will pick up v${p} immediately`))}}catch{}s.stop(w.default.green(`Updated in-place to v${p}`));let E=Q(n,".claude-plugin","plugin.json"),C=null;try{let x=JSON.parse(Wr(E,"utf-8"));x&&typeof x.version=="string"&&(C=x.version)}catch{}if(C!==p)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${C??"<missing>"}" but newVersion is "${p}". Refusing to bump registry.`);r.updatePluginRegistry(n,p),I.info(w.default.dim(" Registry synced to "+n));try{let x=Q(qe(),"plugins","installed_plugins.json");if($e(x)){let P=JSON.parse(Wr(x,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let N of P){let R=N?.installPath;if(typeof R!="string"||!R)continue;if(!$e(R))throw new Error(`installPath does not exist on disk: ${R}`);let O=Q(R,".claude-plugin","plugin.json");if(!$e(O))throw new Error(`missing plugin.json manifest at ${O}`);let F=JSON.parse(Wr(O,"utf-8"));if(F?.version!==N.version)throw new Error(`version mismatch \u2014 registry says "${N.version}" but ${O} says "${F?.version}"`)}}}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`Registry consistency check failed: ${k}`)}try{let x=Q(qe(),"plugins","cache"),k="context-mode@context-mode",P=Fc({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if(P&&P.error)throw new Error(P.error);let N=Fc({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if(N&&Array.isArray(N.healed)&&N.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${N.healed.join(",")})`)}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`plugin.json drift check failed: ${k}`)}try{let x=Q(qe(),"plugins","cache"),k="context-mode@context-mode",P=Hc({pluginCacheRoot:x,pluginKey:k});P&&P.removed&&P.removed.length>0&&I.info(w.default.dim(` Swept ${P.removed.length} stale .mcp.json file(s) from cache`));let N=Hc({pluginCacheRoot:x,pluginKey:k});if(N&&Array.isArray(N.removed)&&N.removed.length>0)throw new Error(`.mcp.json sweep drift: ${N.removed.length} file(s) still present after first pass`)}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`.mcp.json sweep check failed: ${k}`)}try{let{healClaudeJsonMcpArgs:x}=await Promise.resolve().then(()=>(em(),Gv)),k=Q(pd(),".claude.json"),P=Q(qe(),"plugins","cache","context-mode","context-mode"),N=x({dotClaudeJsonPath:k,pluginCacheParent:P,newPluginRoot:n});N.healed&&N.healed.length>0&&I.info(w.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+p))}catch{}try{let x=Q(i,".claude-plugin","plugin.json");if($e(x)){let k=JSON.parse(Wr(x,"utf-8"));k?.version!==p&&(I.warn(w.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${k?.version}" but expected "${p}"`),I.info(w.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(s.start("Installing production dependencies"),ud(["install","--production","--no-audit","--no-fund"],{cwd:n,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),!Xn(e.platform)){s.start("Verifying native addon ABI");let x=Q(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let P=Q(n,"hooks","ensure-deps.mjs");if(!$e(P))throw new Error(`missing ${P}`);await import(`${md(P).href}?upgrade=${Date.now()}`),$e(x)?(s.stop(w.default.green("Native addons OK")+w.default.dim(" \u2014 ABI cache present")),o.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(w.default.yellow("Native addon ABI cache missing")),I.warn(w.default.dim(` Try manually: cd "${n}" && npm rebuild better-sqlite3`)))}catch(P){let N=P instanceof Error?P.message:String(P);s.stop(w.default.yellow("Native addon ABI bootstrap unavailable")),I.warn(w.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${N}`+w.default.dim(`
1196
+ Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let k=Q(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!$e(k))try{let P=Q(n,"scripts","heal-better-sqlite3.mjs");if($e(P)){let N=await import(`${md(P).href}?upgrade=${Date.now()}`);typeof N.healBetterSqlite3Binding=="function"&&N.healBetterSqlite3Binding(n)}}catch{}$e(k)||(process.exitCode=1,I.error(w.default.red("better-sqlite3 native binding: MISSING")+w.default.dim(`
1197
+ Path: ${k}`)+w.default.dim(`
1198
+ Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+w.default.dim(`
1199
+ Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+w.default.dim(`
1200
+ Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{ud(["install","-g",n,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(w.default.green("npm global updated")),o.push("Updated npm global package")}catch{s.stop(w.default.yellow("npm global update skipped")),I.info(w.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}_i(c,{recursive:!0,force:!0});try{let x=qe(),k=Q(x,"plugins","installed_plugins.json");if($e(k)){let P=Q(x,"plugins","cache"),N;try{N=dd(P)}catch{N=P}let R=N+Kr,F=JSON.parse(Wr(k,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(F))for(let K of F){let ge=K?.installPath;if(typeof ge!="string"||!ge||ge===n)continue;let We=Q(ge);if(!(We+Kr).startsWith(R)||!$e(We))continue;let _t;try{_t=dd(We)}catch{continue}if(!(_t+Kr).startsWith(R))continue;let Pr=Q(m,"skills");$e(Pr)&&(vR(Pr,Q(_t,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}catch{}o.push(`Updated v${a} \u2192 v${p}`),I.success(w.default.green("Plugin reinstalled from GitHub!")+w.default.dim(` \u2014 v${p}`))}}catch(m){let h=m instanceof Error?m.message:String(m);s.stop(w.default.red("Update failed")),I.error(w.default.red("GitHub pull failed")+` \u2014 ${h}`),process.exitCode=1,I.warn(w.default.yellow("In-place files were NOT updated")+w.default.dim(" \u2014 old version is still on disk; hooks/settings will still be refreshed.")),I.info(w.default.dim(" Recovery: re-run /ctx-upgrade once network is stable, or run /context-mode:ctx-doctor for a full health check."));try{_i(c,{recursive:!0,force:!0})}catch{}}I.step(`Backing up ${r.name} settings...`);let u=r.backupSettings();u?.endsWith(".bak")?(I.success(w.default.green("Backup created")+w.default.dim(" -> "+u)),o.push("Backed up settings")):u?I.success(w.default.green("Backup skipped")+w.default.dim(" \u2014 no changes needed")):I.warn(w.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),I.step(`Configuring ${r.name} hooks...`);try{let m=r.configureAllHooks(n);for(let h of m)I.info(w.default.dim(` ${h}`)),o.push(h);I.success(w.default.green("Hooks configured")+w.default.dim(` \u2014 ${r.name}`))}catch(m){let h=m instanceof Error?m.message:String(m);throw new Error(`Hook configuration failed: ${h}`)}I.step("Setting hook script permissions...");let l=r.setHookPermissions(n);if(process.platform!=="win32")for(let m of["build/cli.js","cli.bundle.mjs"]){let h=Q(n,m);try{wR(h,$R.F_OK),MZ(h,493),l.push(h)}catch{}}l.length>0?(I.success(w.default.green("Permissions set")+w.default.dim(` \u2014 ${l.length} hook script(s)`)),o.push(`Set ${l.length} hook scripts as executable`)):I.error(w.default.red("No hook scripts found")+w.default.dim(" \u2014 expected in "+Q(n,"hooks"))),o.length>0?mc(o.map(m=>w.default.green(" + ")+m).join(`
1201
+ `),"Changes Applied"):I.info(w.default.dim("No changes were needed."));let d=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";I.warn(w.default.yellow("Restart for new MCP tools to take effect.")+w.default.dim(` (${d})`)),I.step("Running doctor to verify..."),console.log();try{let m=Q(n,"cli.bundle.mjs"),h=Q(n,"build","cli.js"),p=$e(m)?m:h;yi("node",[p,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{I.warn(w.default.yellow("Doctor had warnings")+w.default.dim(` \u2014 restart your ${r.name} session to pick up the new version`))}}function aq(){let t=qe(),e=[Q(Go(),"bin","statusline.mjs"),Q(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=Q(t,"plugins","installed_plugins.json");if($e(n)){let o=Q(t,"plugins","cache"),s;try{s=dd(o)}catch{s=o}let i=s+Kr,c=JSON.parse(Wr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(c))for(let u of c){let l=u?.installPath;if(typeof l!="string"||!l)continue;let d=Q(l);if(!(d+Kr).startsWith(i))continue;let m;try{m=dd(d)}catch{continue}(m+Kr).startsWith(i)&&e.push(Q(m,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>$e(n));r||process.exit(0),import(md(r).href).catch(()=>{process.exit(0)})}export{KZ as npmExec,ud as npmExecFile,GZ as openInBrowser,gY as toUnixPath};