diff --git a/README.md b/README.md index b79616952..c95de4320 100644 --- a/README.md +++ b/README.md @@ -770,6 +770,72 @@ Full documentation: [`docs/adapters/kimi-code.md`](docs/adapters/kimi-code.md) +
+Mistral Vibe — MCP + hooks (TOML config, native [[hooks]] array tables) + +**Prerequisites:** Python 3.12+, [Mistral Vibe](https://github.com/mistralai/mistral-vibe) installed (`uv tool install mistral-vibe`), Node.js >= 22.5 (or Bun). + +1. Install context-mode: + + ```bash + npm install -g context-mode + ``` + +2. Add context-mode as an MCP server. Add to `~/.vibe/config.toml` (or `$VIBE_HOME/config.toml`): + + ```toml + [[mcp_servers]] + name = "context-mode" + transport = "stdio" + command = "context-mode" + ``` + +3. Add hooks to `~/.vibe/hooks.toml` (or `$VIBE_HOME/hooks.toml`): + + ```toml + [[hooks]] + name = "context-mode-pretool" + type = "pre_tool" + match = "bash" + command = "context-mode hook mistral-vibe pretooluse" + timeout = 30.0 + strict = false + description = "Route bash commands through context-mode sandbox" + + [[hooks]] + name = "context-mode-posttool" + type = "post_tool" + command = "context-mode hook mistral-vibe posttooluse" + timeout = 30.0 + strict = false + description = "Capture session events for context-mode" + ``` + + Or run `context-mode upgrade` (with `CONTEXT_MODE_PLATFORM=mistral-vibe`) to have context-mode manage the `hooks.toml` entries for you. The upgrade flow preserves any non-managed hooks (e.g. a user-installed `rtk-rewrite`). + +4. Restart Vibe and verify MCP with `ctx stats`. + +5. (Optional) Copy the routing instructions file for your project: + + ```bash + cp "$(npm root -g)/context-mode/configs/mistral-vibe/AGENTS.md" ./AGENTS.md + ``` + + Vibe reads `AGENTS.md` from the project root by default. + +**Verify:** In a Vibe session, type `ctx stats`. Context-mode tools (namespaced as `context-mode_ctx_*`) should appear and respond. + +**Routing:** `pre_tool` intercepts bash and rewrites `curl`/`wget`/inline HTTP to sandbox tools. `post_tool` captures session events. Auto-detected via `$VIBE_HOME` env var or the presence of `~/.vibe/`. MCP `clientInfo.name` is NOT reliable — Vibe uses the MCP SDK default `"mcp"` because it does not override `client_info`; detection relies on env/config-dir signals instead. + +**Known limitations:** +- Vibe only exposes `pre_tool`, `post_tool`, and `post_agent`. There is no `PreCompact`, `SessionStart`, `UserPromptSubmit`, or `Stop` equivalent — full session-continuity across compactions is not available; the routing block in `AGENTS.md` provides model-side memory queries as a workaround. +- The `pre_tool` `match` field is one string per `[[hooks]]` block. context-mode installs a single `bash`-scoped hook; register additional blocks pointing at the same `pretooluse` command if you need broader tool coverage. +- Coexists with `rtk`: keep `context-mode-pretool` first in `hooks.toml` declaration order so redirected commands never reach rtk. + +Full documentation: [`docs/platform-support.md#mistral-vibe`](docs/platform-support.md#mistral-vibe) + +
+
Qwen Code — MCP + hooks (identical wire protocol to Claude Code) diff --git a/cli.bundle.mjs b/cli.bundle.mjs index cbf9741c4..89049908e 100755 --- a/cli.bundle.mjs +++ b/cli.bundle.mjs @@ -1,8 +1,8 @@ #!/usr/bin/env node -var eO=Object.create;var Ad=Object.defineProperty;var tO=Object.getOwnPropertyDescriptor;var nO=Object.getOwnPropertyNames;var rO=Object.getPrototypeOf,oO=Object.prototype.hasOwnProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),_e=(t,e)=>{for(var n in e)Ad(t,n,{get:e[n],enumerable:!0})},sO=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nO(e))!oO.call(t,o)&&o!==n&&Ad(t,o,{get:()=>e[o],enumerable:!(r=tO(e,o))||r.enumerable});return t};var Si=(t,e,n)=>(n=t!=null?eO(rO(t)):{},sO(e||!t||!t.__esModule?Ad(n,"default",{value:t,enumerable:!0}):n,t));var Ld=L((A9,Zb)=>{"use strict";var jd={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},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"},bO={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},xO={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 n=0;n{var yc=process||{},Gb=yc.argv||[],gc=yc.env||{},qO=!(gc.NO_COLOR||Gb.includes("--no-color"))&&(!!gc.FORCE_COLOR||Gb.includes("--color")||yc.platform==="win32"||(yc.stdout||{}).isTTY&&gc.TERM!=="dumb"||!!gc.CI),VO=(t,e,n=t)=>r=>{let o=""+r,s=o.indexOf(e,t.length);return~s?t+WO(o,e,n,s)+e:t+o+e},WO=(t,e,n,r)=>{let o="",s=0;do o+=t.substring(s,r)+n,s=r+e.length,r=t.indexOf(e,s);while(~r);return o+t.substring(s)},Jb=(t=qO)=>{let e=t?VO:()=>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")}};Zd.exports=Jb();Zd.exports.createColors=Jb});function wi(t,e){let n=process.execPath.replace(/\\/g,"/");if(Jr(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");qd.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function qe(t,e){if(Jr(e?.platform))return wi(t,e);let r=Vd().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function _c(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 Jr(t){return!!t&&KO.has(t)}var qd,KO,Rn=x(()=>{"use strict";Yo();qd=new Set(["node","bun","deno"]),KO=new Set(["opencode","kilo"])});var ox={};_e(ox,{buildCommand:()=>Xd,detectRuntimes:()=>Xr,getAvailableLanguages:()=>$i,getRuntimeSummary:()=>Ti,hasBunRuntime:()=>mr,isAllowlistedShell:()=>Qb,resetHookRuntimeCache:()=>eI,resolveHookRuntime:()=>Vd,resolveJavascriptRuntime:()=>rx});import{execFileSync as Gd,execSync as Qo}from"node:child_process";import{existsSync as es}from"node:fs";function Kd(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function Qb(t){return GO.test(Kd(t))}function JO(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function XO(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function Ke(t){try{let e=Ei?`where ${t}`:`command -v ${t}`;return Qo(e,{stdio:"pipe"}),!0}catch{return!1}}function Wd(t){if(Ei)try{let n=Qo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Ke(t))return!1;try{return Ei?Qo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Gd(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function Jd(){if(Ke("bun"))return!0;for(let t of tx())if(es(t))return!0;return!1}function ex(){for(let e of tx())if(es(e))return e;if(Ke("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Ei?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function tx(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Ei){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function nx(){let t;try{t=Qo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of YO)if(es(r))return r;return e}}return null}function QO(t=nx()){return t??(Ke("sh")?"sh":Ke("pwsh")?"pwsh":Ke("powershell")?"powershell":"cmd.exe")}function Wt(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return Qo(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Gd(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function rx(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??Ke,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return qd.has(o)&&es(n)?n:r("node")?"node":null}function Xr(){let e=Jd()?ex():null,n=process.env.SHELL,r=process.platform==="win32",o=r?nx():null,s=n&&es(n)&&Qb(n)&&!(r&&JO(n))&&!(r&&o&&XO(n))?n:null;return{javascript:rx(e),typescript:e||(Ke("tsx")?"tsx":Ke("ts-node")?"ts-node":null),python:Wd("python3")?"python3":Wd("python")?"python":Wd("py")?"py":null,shell:s??(r?QO(o):Ke("bash")?"bash":"sh"),ruby:Ke("ruby")?"ruby":null,go:Ke("go")?"go":null,rust:Ke("rustc")?"rustc":null,php:Ke("php")?"php":null,perl:Ke("perl")?"perl":null,r:Ke("Rscript")?"Rscript":Ke("r")?"r":null,elixir:Ke("elixir")?"elixir":null,csharp:Ke("dotnet-script")?"dotnet-script":null}}function mr(){return Jd()}function eI(){Ht=null}function tI(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function nI(){return es(process.execPath)?{path:process.execPath,isBun:!1}:Ke("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Vd(){if(Ht)return Ht;let t=nI();try{if(!Jd())return Ht=t,Ht;let e=ex(),n;try{if(process.platform==="win32"){let r=Qo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=Gd(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ht=t,Ht}return tI(n)?(Ht={path:e,isBun:!0},Ht):(Ht=t,Ht)}catch{return Ht=t,Ht}}function Ti(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Wt(t.javascript)})${n?" \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)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(` -`)}function $i(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 Xd(t,e,n){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 Yb.test(Kd(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];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 Yb.test(Kd(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var GO,Yb,Ei,YO,Ht,Yo=x(()=>{"use strict";Rn();GO=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Yb=/^bun(\.exe)?$/i;Ei=process.platform==="win32";YO=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Ht=null});function rI(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function oI(t){let e=_c(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function bc(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of rI(s)){let a=oI(i);a&&n.add(a)}return[...n]}var Yd=x(()=>{"use strict";Rn()});var sx,ix=x(()=>{"use strict";sx={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","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 tp={};_e(tp,{BunSQLiteAdapter:()=>xc,NodeSQLiteAdapter:()=>Sc,SQLiteBase:()=>Ri,applyWALPragmas:()=>ns,cleanOrphanedWALFiles:()=>rs,closeDB:()=>os,defaultDBPath:()=>ep,deleteDBFiles:()=>vc,hasModernSqlite:()=>ux,isSQLiteCorruptionError:()=>kc,loadDatabase:()=>nt,nodeSqliteHasFts5:()=>cx,renameCorruptDB:()=>lx,withRetry:()=>fr});import{createRequire as sI}from"node:module";import{existsSync as iI,unlinkSync as ax,renameSync as aI}from"node:fs";import{tmpdir as cI}from"node:os";import{join as uI}from"node:path";function cx(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 ux(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.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 nt(){if(!ts){let t=sI(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;ts=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new xc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(ux()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&cx(e)?ts=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new Sc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:ts=t("better-sqlite3")}else ts=t("better-sqlite3")}return ts}function ns(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function rs(t){if(!iI(t))for(let e of["-wal","-shm"])try{ax(t+e)}catch{}}function vc(t){for(let e of["","-wal","-shm"])try{ax(t+e)}catch{}}function os(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ep(t="context-mode"){return uI(cI(),`${t}-${process.pid}.db`)}function fr(t,e=[100,500,2e3]){let n;for(let r=0;r<=e.length;r++)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(n=o instanceof Error?o:new Error(s),r{"use strict";xc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;sn.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},Sc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},ts=null;Pi=Symbol.for("__context_mode_live_dbs_v3__"),Qd=(()=>{let t=globalThis;return t[Pi]||(t[Pi]=new Set,process.on("exit",()=>{for(let e of t[Pi])os(e);t[Pi].clear()})),t[Pi]})(),Ri=class{#e;#t;constructor(e){let n=nt();this.#e=e,rs(e);let r;try{r=new n(e,{timeout:3e4}),ns(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(kc(s)){lx(e),rs(e);try{r=new n(e,{timeout:3e4}),ns(r)}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=r,Qd.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Qd.delete(this.#t),os(this.#t)}withRetry(e){return fr(e)}cleanup(){Qd.delete(this.#t),os(this.#t),vc(this.#e)}}});var wx={};_e(wx,{SessionDB:()=>Gt,StorageDirectoryError:()=>Kt,_resetWorktreeSuffixCacheForTests:()=>TI,applyMissingSessionEventsColumns:()=>op,clearStorageDirectoryCheckCacheForTests:()=>xI,describeStorageDirectorySource:()=>Oi,ensureSessionEventsSchema:()=>sp,ensureWritableStorageDir:()=>br,formatStorageDirectoryError:()=>cs,getWorktreeSuffix:()=>Ii,hashProjectDirCanonical:()=>rt,hashProjectDirLegacy:()=>On,normalizeWorktreePath:()=>yr,resolveContentStorageDir:()=>Yr,resolveContentStorePath:()=>rp,resolveDefaultSessionDir:()=>$c,resolveSessionDbPath:()=>us,resolveSessionPath:()=>kx,resolveSessionStorageDir:()=>_r,resolveStatsStorageDir:()=>as});import{createHash as Ci}from"node:crypto";import{execFileSync as lI}from"node:child_process";import{accessSync as dI,constants as pI,existsSync as Tc,mkdirSync as mI,realpathSync as fI,renameSync as np}from"node:fs";import{homedir as gx}from"node:os";import{dirname as hI,isAbsolute as yx,join as gr,resolve as is}from"node:path";function $c(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):gr(gI(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function gI(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?px(r.trim()):px(t,gx())}function px(t,e){return t.startsWith("~")?is(gx(),t.replace(/^~[/\\]?/,"")):yx(t)?is(t):e?is(e,t):is(t)}function yI(t,e,n){return new Kt(t,e,Cn,void 0,[`Invalid ${Cn} for context-mode ${t} directory: ${n}`,Sx()].join(` -`))}function bx(t){let e=process.env[Cn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:Cn,ignoredReason:"empty"};if(!yx(n))throw yI(t,n,`${Cn} must be an absolute path.`);return{kind:"override",root:is(n)}}function _I(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function xx(t,e){let n=bx(t);return n.kind!=="override"?null:{kind:t,path:gr(n.root,e),envVar:Cn,source:"override"}}function bI(t,e,n){return{kind:t,path:is(e()),envVar:null,source:"default",...n}}function _r(t){let e=bx("session");return e.kind==="override"?{kind:"session",path:gr(e.root,_x),envVar:Cn,source:"override"}:bI("session",t,_I(e))}function Yr(t){let e=xx("content",dx);if(e)return e;let n=_r(t);return{kind:"content",path:gr(hI(n.path),dx),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function as(t){let e=xx("stats",_x);if(e)return e;let n=_r(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function cs(t){return t.message}function Oi(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function xI(){Ec.clear()}function br(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=Ec.get(e);if(n instanceof Kt)throw n;if(n===t.path)return n;try{return mI(t.path,{recursive:!0}),dI(t.path,pI.W_OK),Ec.set(e,t.path),t.path}catch(r){let o=new Kt(t.kind,kI(r)??t.path,Cn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Ec.set(e,o),o}}function SI(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,vI(n),Sx()].filter(Boolean).join(` -`)}function vI(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function Sx(){return`Set ${Cn} to a writable absolute path.`}function kI(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function yr(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function mx(t){let e=t;try{e=fI.native(t)}catch{}let n=yr(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function vx(t,e){return lI("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function wI(t){let e=vx(t,["rev-parse","--show-toplevel"]);return e.length>0?yr(e):null}function EI(t){let e=vx(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?yr(e):null}function Ii(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(ss&&ss.projectDir===t&&ss.envSuffix===e)return ss.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=wI(t),o=EI(t);if(r&&o){let s=mx(r),i=mx(o);s!==i&&(n=`__${Ci("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return ss={projectDir:t,envSuffix:e,suffix:n},n}function TI(){ss=void 0}function On(t){return Ci("sha256").update(yr(t)).digest("hex").slice(0,16)}function rt(t){let e=yr(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Ci("sha256").update(n).digest("hex").slice(0,16)}function rp(t){let{projectDir:e,contentDir:n}=t,r=rt(e),o=gr(n,`${r}.db`);if(Tc(o))return o;let s=On(e);if(s===r)return o;let i=gr(n,`${s}.db`);if(Tc(i))try{np(i,o);for(let a of["-wal","-shm"])try{np(i+a,o+a)}catch{}}catch{}return o}function us(t){return kx({...t,ext:".db"})}function kx(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??Ii(e),s=rt(e),i=gr(n,`${s}${o}${r}`);if(Tc(i))return i;let a=On(e);if(a===s)return i;let c=gr(n,`${a}${o}${r}`);if(Tc(c))try{np(c,i)}catch{}return i}function wc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function op(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of $I)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function sp(t,e){let n=null;try{n=new e(t),op(n)}catch{}finally{try{n?.close()}catch{}}}var Cn,_x,dx,Kt,Ec,ss,fx,hx,F,$I,Gt,Jt=x(()=>{"use strict";hr();Cn="CONTEXT_MODE_DIR",_x="sessions",dx="content",Kt=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=Cn,o,s,i={}){super(s??SI(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},Ec=new Map;fx=1e3,hx=5;F={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",getUsageCursor:"getUsageCursor",setUsageCursor:"setUsageCursor",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"},$I=[["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 Ri{constructor(e){super(e?.dbPath??ep("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=this.db.pragma("table_xinfo(session_events)").find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(` +var yO=Object.create;var zd=Object.defineProperty;var _O=Object.getOwnPropertyDescriptor;var bO=Object.getOwnPropertyNames;var xO=Object.getPrototypeOf,vO=Object.prototype.hasOwnProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ye=(t,e)=>{for(var n in e)zd(t,n,{get:e[n],enumerable:!0})},SO=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of bO(e))!vO.call(t,o)&&o!==n&&zd(t,o,{get:()=>e[o],enumerable:!(r=_O(e,o))||r.enumerable});return t};var ki=(t,e,n)=>(n=t!=null?yO(xO(t)):{},SO(e||!t||!t.__esModule?zd(n,"default",{value:t,enumerable:!0}):n,t));var Zd=L((o9,ex)=>{"use strict";var Bd={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},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"},DO={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},jO={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 n=0;n{var xc=process||{},sx=xc.argv||[],bc=xc.env||{},cI=!(bc.NO_COLOR||sx.includes("--no-color"))&&(!!bc.FORCE_COLOR||sx.includes("--color")||xc.platform==="win32"||(xc.stdout||{}).isTTY&&bc.TERM!=="dumb"||!!bc.CI),uI=(t,e,n=t)=>r=>{let o=""+r,s=o.indexOf(e,t.length);return~s?t+lI(o,e,n,s)+e:t+o+e},lI=(t,e,n,r)=>{let o="",s=0;do o+=t.substring(s,r)+n,s=r+e.length,r=t.indexOf(e,s);while(~r);return o+t.substring(s)},ix=(t=cI)=>{let e=t?uI:()=>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")}};Jd.exports=ix();Jd.exports.createColors=ix});function Ti(t,e){let n=process.execPath.replace(/\\/g,"/");if(Jr(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Xd.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function qe(t,e){if(Jr(e?.platform))return Ti(t,e);let r=Yd().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function vc(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 Jr(t){return!!t&&dI.has(t)}var Xd,dI,Pn=x(()=>{"use strict";es();Xd=new Set(["node","bun","deno"]),dI=new Set(["opencode","kilo"])});var fx={};ye(fx,{buildCommand:()=>rp,detectRuntimes:()=>Xr,getAvailableLanguages:()=>Ri,getRuntimeSummary:()=>Pi,hasBunRuntime:()=>mr,isAllowlistedShell:()=>ux,resetHookRuntimeCache:()=>yI,resolveHookRuntime:()=>Yd,resolveJavascriptRuntime:()=>mx});import{execFileSync as tp,execSync as ts}from"node:child_process";import{existsSync as ns}from"node:fs";function ep(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function ux(t){return pI.test(ep(t))}function mI(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function fI(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function Ke(t){try{let e=$i?`where ${t}`:`command -v ${t}`;return ts(e,{stdio:"pipe"}),!0}catch{return!1}}function Qd(t){if($i)try{let n=ts(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Ke(t))return!1;try{return $i?ts(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):tp(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function np(){if(Ke("bun"))return!0;for(let t of dx())if(ns(t))return!0;return!1}function lx(){for(let e of dx())if(ns(e))return e;if(Ke("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return $i?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function dx(){let t=process.env.HOME??process.env.USERPROFILE??"";if($i){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function px(){let t;try{t=ts("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of hI)if(ns(r))return r;return e}}return null}function gI(t=px()){return t??(Ke("sh")?"sh":Ke("pwsh")?"pwsh":Ke("powershell")?"powershell":"cmd.exe")}function Kt(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return ts(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return tp(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function mx(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??Ke,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Xd.has(o)&&ns(n)?n:r("node")?"node":null}function Xr(){let e=np()?lx():null,n=process.env.SHELL,r=process.platform==="win32",o=r?px():null,s=n&&ns(n)&&ux(n)&&!(r&&mI(n))&&!(r&&o&&fI(n))?n:null;return{javascript:mx(e),typescript:e||(Ke("tsx")?"tsx":Ke("ts-node")?"ts-node":null),python:Qd("python3")?"python3":Qd("python")?"python":Qd("py")?"py":null,shell:s??(r?gI(o):Ke("bash")?"bash":"sh"),ruby:Ke("ruby")?"ruby":null,go:Ke("go")?"go":null,rust:Ke("rustc")?"rustc":null,php:Ke("php")?"php":null,perl:Ke("perl")?"perl":null,r:Ke("Rscript")?"Rscript":Ke("r")?"r":null,elixir:Ke("elixir")?"elixir":null,csharp:Ke("dotnet-script")?"dotnet-script":null}}function mr(){return np()}function yI(){Ht=null}function _I(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function bI(){return ns(process.execPath)?{path:process.execPath,isBun:!1}:Ke("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Yd(){if(Ht)return Ht;let t=bI();try{if(!np())return Ht=t,Ht;let e=lx(),n;try{if(process.platform==="win32"){let r=ts(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=tp(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ht=t,Ht}return _I(n)?(Ht={path:e,isBun:!0},Ht):(Ht=t,Ht)}catch{return Ht=t,Ht}}function Pi(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Kt(t.javascript)})${n?" \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} (${Kt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Kt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Kt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Kt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Kt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Kt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Kt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Kt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Kt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Kt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Kt(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(` +`)}function Ri(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 rp(t,e,n){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 cx.test(ep(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];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 cx.test(ep(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var pI,cx,$i,hI,Ht,es=x(()=>{"use strict";Pn();pI=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,cx=/^bun(\.exe)?$/i;$i=process.platform==="win32";hI=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Ht=null});function xI(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function vI(t){let e=vc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function Sc(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of xI(s)){let a=vI(i);a&&n.add(a)}return[...n]}var op=x(()=>{"use strict";Pn()});var hx,gx=x(()=>{"use strict";hx={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","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","mistral-vibe":"mistral-vibe","Mistral Vibe":"mistral-vibe",vibe:"mistral-vibe"}});var ap={};ye(ap,{BunSQLiteAdapter:()=>kc,NodeSQLiteAdapter:()=>wc,SQLiteBase:()=>Oi,applyWALPragmas:()=>os,cleanOrphanedWALFiles:()=>ss,closeDB:()=>is,defaultDBPath:()=>ip,deleteDBFiles:()=>Ec,hasModernSqlite:()=>bx,isSQLiteCorruptionError:()=>Tc,loadDatabase:()=>ot,nodeSqliteHasFts5:()=>_x,renameCorruptDB:()=>xx,withRetry:()=>fr});import{createRequire as SI}from"node:module";import{existsSync as kI,unlinkSync as yx,renameSync as wI}from"node:fs";import{tmpdir as EI}from"node:os";import{join as TI}from"node:path";function _x(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 bx(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.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 ot(){if(!rs){let t=SI(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;rs=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new kc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(bx()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&_x(e)?rs=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new wc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:rs=t("better-sqlite3")}else rs=t("better-sqlite3")}return rs}function os(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function ss(t){if(!kI(t))for(let e of["-wal","-shm"])try{yx(t+e)}catch{}}function Ec(t){for(let e of["","-wal","-shm"])try{yx(t+e)}catch{}}function is(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ip(t="context-mode"){return TI(EI(),`${t}-${process.pid}.db`)}function fr(t,e=[100,500,2e3]){let n;for(let r=0;r<=e.length;r++)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(n=o instanceof Error?o:new Error(s),r{"use strict";kc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;sn.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},wc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},rs=null;Ci=Symbol.for("__context_mode_live_dbs_v3__"),sp=(()=>{let t=globalThis;return t[Ci]||(t[Ci]=new Set,process.on("exit",()=>{for(let e of t[Ci])is(e);t[Ci].clear()})),t[Ci]})(),Oi=class{#e;#t;constructor(e){let n=ot();this.#e=e,ss(e);let r;try{r=new n(e,{timeout:3e4}),os(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Tc(s)){xx(e),ss(e);try{r=new n(e,{timeout:3e4}),os(r)}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=r,sp.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){sp.delete(this.#t),is(this.#t)}withRetry(e){return fr(e)}cleanup(){sp.delete(this.#t),is(this.#t),Ec(this.#e)}}});var Nx={};ye(Nx,{SessionDB:()=>Jt,StorageDirectoryError:()=>Gt,_resetWorktreeSuffixCacheForTests:()=>BI,applyMissingSessionEventsColumns:()=>lp,clearStorageDirectoryCheckCacheForTests:()=>jI,describeStorageDirectorySource:()=>Ai,ensureSessionEventsSchema:()=>dp,ensureWritableStorageDir:()=>br,formatStorageDirectoryError:()=>ls,getWorktreeSuffix:()=>Ni,hashProjectDirCanonical:()=>Ge,hashProjectDirLegacy:()=>Cn,normalizeWorktreePath:()=>yr,resolveContentStorageDir:()=>Yr,resolveContentStorePath:()=>up,resolveDefaultSessionDir:()=>Cc,resolveSessionDbPath:()=>ds,resolveSessionPath:()=>Ax,resolveSessionStorageDir:()=>_r,resolveStatsStorageDir:()=>us});import{createHash as Ii}from"node:crypto";import{execFileSync as $I}from"node:child_process";import{accessSync as PI,constants as RI,existsSync as Rc,mkdirSync as CI,realpathSync as OI,renameSync as cp}from"node:fs";import{homedir as Tx}from"node:os";import{dirname as II,isAbsolute as $x,join as gr,resolve as cs}from"node:path";function Cc(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):gr(AI(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function AI(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?Sx(r.trim()):Sx(t,Tx())}function Sx(t,e){return t.startsWith("~")?cs(Tx(),t.replace(/^~[/\\]?/,"")):$x(t)?cs(t):e?cs(e,t):cs(t)}function NI(t,e,n){return new Gt(t,e,Rn,void 0,[`Invalid ${Rn} for context-mode ${t} directory: ${n}`,Ox()].join(` +`))}function Rx(t){let e=process.env[Rn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:Rn,ignoredReason:"empty"};if(!$x(n))throw NI(t,n,`${Rn} must be an absolute path.`);return{kind:"override",root:cs(n)}}function MI(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function Cx(t,e){let n=Rx(t);return n.kind!=="override"?null:{kind:t,path:gr(n.root,e),envVar:Rn,source:"override"}}function DI(t,e,n){return{kind:t,path:cs(e()),envVar:null,source:"default",...n}}function _r(t){let e=Rx("session");return e.kind==="override"?{kind:"session",path:gr(e.root,Px),envVar:Rn,source:"override"}:DI("session",t,MI(e))}function Yr(t){let e=Cx("content",vx);if(e)return e;let n=_r(t);return{kind:"content",path:gr(II(n.path),vx),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function us(t){let e=Cx("stats",Px);if(e)return e;let n=_r(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function ls(t){return t.message}function Ai(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function jI(){Pc.clear()}function br(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=Pc.get(e);if(n instanceof Gt)throw n;if(n===t.path)return n;try{return CI(t.path,{recursive:!0}),PI(t.path,RI.W_OK),Pc.set(e,t.path),t.path}catch(r){let o=new Gt(t.kind,HI(r)??t.path,Rn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Pc.set(e,o),o}}function LI(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,zI(n),Ox()].filter(Boolean).join(` +`)}function zI(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function Ox(){return`Set ${Rn} to a writable absolute path.`}function HI(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function yr(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function kx(t){let e=t;try{e=OI.native(t)}catch{}let n=yr(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function Ix(t,e){return $I("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function UI(t){let e=Ix(t,["rev-parse","--show-toplevel"]);return e.length>0?yr(e):null}function FI(t){let e=Ix(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?yr(e):null}function Ni(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(as&&as.projectDir===t&&as.envSuffix===e)return as.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=UI(t),o=FI(t);if(r&&o){let s=kx(r),i=kx(o);s!==i&&(n=`__${Ii("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return as={projectDir:t,envSuffix:e,suffix:n},n}function BI(){as=void 0}function Cn(t){return Ii("sha256").update(yr(t)).digest("hex").slice(0,16)}function Ge(t){let e=yr(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Ii("sha256").update(n).digest("hex").slice(0,16)}function up(t){let{projectDir:e,contentDir:n}=t,r=Ge(e),o=gr(n,`${r}.db`);if(Rc(o))return o;let s=Cn(e);if(s===r)return o;let i=gr(n,`${s}.db`);if(Rc(i))try{cp(i,o);for(let a of["-wal","-shm"])try{cp(i+a,o+a)}catch{}}catch{}return o}function ds(t){return Ax({...t,ext:".db"})}function Ax(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??Ni(e),s=Ge(e),i=gr(n,`${s}${o}${r}`);if(Rc(i))return i;let a=Cn(e);if(a===s)return i;let c=gr(n,`${a}${o}${r}`);if(Rc(c))try{cp(c,i)}catch{}return i}function $c(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function lp(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of ZI)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function dp(t,e){let n=null;try{n=new e(t),lp(n)}catch{}finally{try{n?.close()}catch{}}}var Rn,Px,vx,Gt,Pc,as,wx,Ex,F,ZI,Jt,Ut=x(()=>{"use strict";hr();Rn="CONTEXT_MODE_DIR",Px="sessions",vx="content",Gt=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=Rn,o,s,i={}){super(s??LI(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},Pc=new Map;wx=1e3,Ex=5;F={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",getUsageCursor:"getUsageCursor",setUsageCursor:"setUsageCursor",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"},ZI=[["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"]];Jt=class extends Oi{constructor(e){super(e?.dbPath??ip("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=this.db.pragma("table_xinfo(session_events)").find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(` CREATE TABLE IF NOT EXISTS session_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, @@ -52,7 +52,7 @@ var eO=Object.create;var Ad=Object.defineProperty;var tO=Object.getOwnPropertyDe ); CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id); - `);try{op(this.db)}catch{}try{this.db.pragma("table_xinfo(session_meta)").some(n=>n.name==="usage_cursor")||this.db.exec("ALTER TABLE session_meta ADD COLUMN usage_cursor TEXT")}catch{}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(F.insertEvent,`INSERT INTO session_events ( + `);try{lp(this.db)}catch{}try{this.db.pragma("table_xinfo(session_meta)").some(n=>n.name==="usage_cursor")||this.db.exec("ALTER TABLE session_meta ADD COLUMN usage_cursor TEXT")}catch{}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(F.insertEvent,`INSERT INTO session_events ( session_id, type, category, priority, data, project_dir, attribution_source, attribution_confidence, bytes_avoided, bytes_returned, @@ -141,51 +141,55 @@ var eO=Object.create;var Ad=Object.defineProperty;var tO=Object.getOwnPropertyDe FROM tool_calls WHERE session_id = ?`),e(F.getToolCallByTool,`SELECT tool, calls, bytes_returned FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(F.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided, COALESCE(SUM(bytes_returned), 0) AS bytes_returned - FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Ci("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=wc(s?.bytesAvoided),p=wc(s?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(F.checkDuplicate).get(e,hx,n.type,i))return;this.stmt(F.getEventCount).get(e).cnt>=fx&&this.stmt(F.evictLowestPriority).run(e),this.stmt(F.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,p,r,i),this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Ci("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],p=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),f=p===""?"":yr(p),m=String(d?.source??c.attribution_source??"unknown"),h=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(h)?Math.max(0,Math.min(1,h)):0,y=s?.[u],_=wc(y?.bytesAvoided),b=wc(y?.bytesReturned);return{event:c,dataHash:l,projectDir:f,attributionSource:m,attributionConfidence:g,bytesAvoided:_,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(F.getEventCount).get(e).cnt;for(let u of i)this.stmt(F.checkDuplicate).get(e,hx,u.event.type,u.dataHash)||(c>=fx?this.stmt(F.evictLowestPriority).run(e):c++,this.stmt(F.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,r,u.dataHash));this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(F.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(F.getEventsByType).all(e,o,r):s!==void 0?this.stmt(F.getEventsByPriority).all(e,s,r):this.stmt(F.getEvents).all(e,r)}getEventCount(e){return this.stmt(F.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(F.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(F.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,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(F.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=yr(e);return this.db.prepare(`SELECT DISTINCT session_id + FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Ii("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=$c(s?.bytesAvoided),p=$c(s?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(F.checkDuplicate).get(e,Ex,n.type,i))return;this.stmt(F.getEventCount).get(e).cnt>=wx&&this.stmt(F.evictLowestPriority).run(e),this.stmt(F.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,p,r,i),this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Ii("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],p=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),f=p===""?"":yr(p),m=String(d?.source??c.attribution_source??"unknown"),h=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(h)?Math.max(0,Math.min(1,h)):0,y=s?.[u],_=$c(y?.bytesAvoided),b=$c(y?.bytesReturned);return{event:c,dataHash:l,projectDir:f,attributionSource:m,attributionConfidence:g,bytesAvoided:_,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(F.getEventCount).get(e).cnt;for(let u of i)this.stmt(F.checkDuplicate).get(e,Ex,u.event.type,u.dataHash)||(c>=wx?this.stmt(F.evictLowestPriority).run(e):c++,this.stmt(F.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,r,u.dataHash));this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(F.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(F.getEventsByType).all(e,o,r):s!==void 0?this.stmt(F.getEventsByPriority).all(e,s,r):this.stmt(F.getEvents).all(e,r)}getEventCount(e){return this.stmt(F.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(F.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(F.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,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(F.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=yr(e);return this.db.prepare(`SELECT DISTINCT session_id FROM session_events - WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(F.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(F.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(F.getSessionRollup).get(e),r=this.stmt(F.getMaxFileEdits).get(e),o=this.stmt(F.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(F.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(F.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(F.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(F.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(F.getResume).get(e)??null}markResumeConsumed(e){this.stmt(F.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(F.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.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,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(F.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(F.getToolCallTotals).get(e),r=this.stmt(F.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(F.deleteEvents).run(e),this.stmt(F.deleteResume).run(e),this.stmt(F.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(F.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.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 ls,resolve as Ex}from"node:path";import{accessSync as PI,copyFileSync as RI,constants as CI,mkdirSync as OI}from"node:fs";import{homedir as ip}from"node:os";function ht(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?Ex(ip(),e.replace(/^~[/\\]?/,"")):Ex(e)}var ve,it=x(()=>{"use strict";Jt();ve=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=ht(),n=e?ls(e,"context-mode","sessions"):ls(ip(),...this.sessionDirSegments,"context-mode","sessions");return OI(n,{recursive:!0}),n}getConfigDir(e){return ls(ip(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=ht(),r=n?ls(n,"context-mode","memory"):ls(this.getConfigDir(),"memory");return e?ls(r,rt(e)):r}backupSettings(){let e=this.getSettingsPath();try{PI(e,CI.R_OK);let n=e+".bak";return RI(e,n),n}catch{return null}}}});var ds,ap=x(()=>{"use strict";it();ds=class extends ve{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as cp}from"node:fs";import{join as up}from"node:path";async function II(){if(ps)return ps;if(ms)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 n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return ps=r,ps}catch(r){e=r}return ms=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return ms=t instanceof Error?t.message:String(t),null}}function AI(t){let e=[];return cp(up(t,"start.mjs"))||e.push("start.mjs"),!cp(up(t,"server.bundle.mjs"))&&!cp(up(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Tx(t){if(ps){let e=ps.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(ms){let e=AI(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${ms}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${ms}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ps,ms,$x=x(()=>{"use strict";ps=null,ms=null;II()});function Ai(t,e){let n=Qr[e],r=dp(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function dp(t,e){if(e){let n=Qr[t];return qe(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function pp(t){let e=_c(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function Cx(t){let e=Object.values(Qr);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Xt,NI,lp,Px,MI,GV,Qr,Rx,JV,Ox=x(()=>{"use strict";Rn();Xt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},NI="mcp__",lp=["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",NI],Px=lp.join("|"),MI=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],GV=MI.join("|"),Qr={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Rx=[Xt.PRE_TOOL_USE,Xt.SESSION_START],JV=[Xt.POST_TOOL_USE,Xt.PRE_COMPACT,Xt.USER_PROMPT_SUBMIT,Xt.STOP]});var fp={};_e(fp,{ClaudeCodeAdapter:()=>mp});import{readFileSync as Pc,writeFileSync as Ix,existsSync as Ax,readdirSync as DI,chmodSync as jI,accessSync as LI,mkdirSync as zI,constants as HI}from"node:fs";import{resolve as Rc,join as xr}from"node:path";import{homedir as Nx}from"node:os";var mp,hp=x(()=>{"use strict";ap();it();Sr();$x();Rn();Ox();mp=class extends ds{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 Be()}getSessionDir(){let e=ht(),n=e?xr(e,"context-mode","sessions"):xr(this.getConfigDir(),"context-mode","sessions");return zI(n,{recursive:!0}),n}getSettingsPath(){return xr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=qe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...lp].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=Pc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Ix(this.getSettingsPath(),JSON.stringify(e,null,2)+` -`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Xt.PRE_TOOL_USE);n.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,Xt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(Qr).map(([o,s])=>{let i=xr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>Ax(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>Tx(e)};return[...n,r]}readPluginHooks(e){let n=[xr(e,"hooks","hooks.json"),xr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=Pc(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Ai(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Ai(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=xr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Pc(n,"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(),Be(),Rc(Nx(),".claude"),Rc(Nx(),".config","claude")]));for(let n of e){let r=Rc(n,"plugins","cache","context-mode","context-mode");try{let s=DI(r).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 n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(f=>{let m=f;if(!Cx(m))return!0;let h=m.hooks??[];return h.every(y=>!y.command||!pp(y.command))?!0:h.every(y=>{let _=y.command?pp(y.command):null;return _?Ax(_):!0})}),p=l.length-d.length;p>0&&(r[u]=d,o.push(`Removed ${p} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&Rx.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(Qr),d=p=>p!=null&&(l.some(f=>p.includes(f))||p.includes("context-mode hook"));for(let p of Object.keys(r)){let f=r[p];if(!Array.isArray(f))continue;let m=0;for(let g of f){let y=g,_=y.hooks??[],b=_.length;y.hooks=_.filter(S=>!d(S.command)),m+=b-y.hooks.length}let h=f.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(m>0||h.length!==f.length)&&(r[p]=h,m>0&&o.push(`Removed ${m} duplicate ${p} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Xt.PRE_TOOL_USE,Xt.SESSION_START];for(let u of c){let l=dp(u,e);if(u===Xt.PRE_TOOL_USE){let d={matcher:Px,hooks:[{type:"command",command:l}]},p=r.PreToolUse;if(p&&Array.isArray(p)){let f=p.findIndex(m=>Ai(m,u));f>=0?(p[f]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=p}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},p=r[u];if(p&&Array.isArray(p)){let f=p.findIndex(m=>Ai(m,u));f>=0?(p[f]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r[u]=p}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(Qr)){let o=Rc(e,"hooks",r);try{LI(o,HI.R_OK),jI(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=xr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Pc(r,"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=n,a.lastUpdated=new Date().toISOString();Ix(r,JSON.stringify(o,null,2)+` -`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function vr(t,e){let n=Cc[t];return e&&n?qe(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var be,Mx,Cc,cW,uW,Dx=x(()=>{"use strict";Rn();be={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",AFTER_MODEL:"AfterModel",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Mx="mcp__(?!.*context-mode)",Cc={[be.BEFORE_AGENT]:"beforeagent.mjs",[be.BEFORE_TOOL]:"beforetool.mjs",[be.AFTER_TOOL]:"aftertool.mjs",[be.AFTER_MODEL]:"aftermodel.mjs",[be.PRE_COMPRESS]:"precompress.mjs",[be.SESSION_START]:"sessionstart.mjs"},cW=[be.BEFORE_TOOL,be.SESSION_START],uW=[be.AFTER_TOOL,be.AFTER_MODEL,be.PRE_COMPRESS]});var zx={};_e(zx,{GeminiCLIAdapter:()=>yp});import{readFileSync as gp,writeFileSync as jx,mkdirSync as UI,accessSync as FI,chmodSync as BI,existsSync as ZI,constants as qI}from"node:fs";import{resolve as Ni,join as Lx}from"node:path";import{homedir as Oc}from"node:os";var yp,Hx=x(()=>{"use strict";it();Dx();yp=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 Ni(Oc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[be.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:vr(be.BEFORE_AGENT,e)}]}],[be.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|${Mx}`,hooks:[{type:"command",command:vr(be.BEFORE_TOOL,e)}]}],[be.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:vr(be.AFTER_TOOL,e)}]}],[be.AFTER_MODEL]:[{matcher:"",hooks:[{type:"command",command:vr(be.AFTER_MODEL,e)}]}],[be.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:vr(be.PRE_COMPRESS,e)}]}],[be.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:vr(be.SESSION_START,e)}]}]}}readSettings(){try{let e=gp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Ni(Oc(),".gemini");UI(n,{recursive:!0}),jx(this.getSettingsPath(),JSON.stringify(e,null,2)+` -`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[be.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[be.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(Cc).map(([n,r])=>{let o=Lx(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>ZI(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 n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).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=Ni(Oc(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(gp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:be.BEFORE_AGENT},{name:be.BEFORE_TOOL},{name:be.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:vr(i.name,e)}]},u=r[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(f=>f.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`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=Lx(e,"hooks","gemini-cli");for(let o of Object.values(Cc)){let s=Ni(r,o);try{FI(s,qI.R_OK),BI(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Ni(Oc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(gp(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),jx(r,JSON.stringify(o,null,2)+` -`,"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}`}}});function Mi(t){let e="",n=!1,r=!1,o=!1;for(let c=0;co.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(F.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(F.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(F.getSessionRollup).get(e),r=this.stmt(F.getMaxFileEdits).get(e),o=this.stmt(F.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(F.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(F.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(F.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(F.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(F.getResume).get(e)??null}markResumeConsumed(e){this.stmt(F.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(F.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.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,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(F.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(F.getToolCallTotals).get(e),r=this.stmt(F.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(F.deleteEvents).run(e),this.stmt(F.deleteResume).run(e),this.stmt(F.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(F.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.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 ps,resolve as Mx}from"node:path";import{accessSync as qI,copyFileSync as VI,constants as WI,mkdirSync as KI}from"node:fs";import{homedir as pp}from"node:os";function et(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?Mx(pp(),e.replace(/^~[/\\]?/,"")):Mx(e)}var _e,st=x(()=>{"use strict";Ut();_e=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=et(),n=e?ps(e,"context-mode","sessions"):ps(pp(),...this.sessionDirSegments,"context-mode","sessions");return KI(n,{recursive:!0}),n}getConfigDir(e){return ps(pp(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=et(),r=n?ps(n,"context-mode","memory"):ps(this.getConfigDir(),"memory");return e?ps(r,Ge(e)):r}backupSettings(){let e=this.getSettingsPath();try{qI(e,WI.R_OK);let n=e+".bak";return VI(e,n),n}catch{return null}}}});var ms,mp=x(()=>{"use strict";st();ms=class extends _e{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as fp}from"node:fs";import{join as hp}from"node:path";async function GI(){if(fs)return fs;if(hs)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 n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return fs=r,fs}catch(r){e=r}return hs=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return hs=t instanceof Error?t.message:String(t),null}}function JI(t){let e=[];return fp(hp(t,"start.mjs"))||e.push("start.mjs"),!fp(hp(t,"server.bundle.mjs"))&&!fp(hp(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Dx(t){if(fs){let e=fs.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(hs){let e=JI(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${hs}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${hs}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var fs,hs,jx=x(()=>{"use strict";fs=null,hs=null;GI()});function Mi(t,e){let n=Qr[e],r=yp(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function yp(t,e){if(e){let n=Qr[t];return qe(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function _p(t){let e=vc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function Hx(t){let e=Object.values(Qr);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Xt,XI,gp,Lx,YI,xW,Qr,zx,vW,Ux=x(()=>{"use strict";Pn();Xt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},XI="mcp__",gp=["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",XI],Lx=gp.join("|"),YI=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],xW=YI.join("|"),Qr={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},zx=[Xt.PRE_TOOL_USE,Xt.SESSION_START],vW=[Xt.POST_TOOL_USE,Xt.PRE_COMPACT,Xt.USER_PROMPT_SUBMIT,Xt.STOP]});var xp={};ye(xp,{ClaudeCodeAdapter:()=>bp});import{readFileSync as Oc,writeFileSync as Fx,existsSync as Bx,readdirSync as QI,chmodSync as eA,accessSync as tA,mkdirSync as nA,constants as rA}from"node:fs";import{resolve as Ic,join as xr}from"node:path";import{homedir as Zx}from"node:os";var bp,vp=x(()=>{"use strict";mp();st();vr();jx();Pn();Ux();bp=class extends ms{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 Be()}getSessionDir(){let e=et(),n=e?xr(e,"context-mode","sessions"):xr(this.getConfigDir(),"context-mode","sessions");return nA(n,{recursive:!0}),n}getSettingsPath(){return xr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=qe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...gp].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=Oc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Fx(this.getSettingsPath(),JSON.stringify(e,null,2)+` +`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Xt.PRE_TOOL_USE);n.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,Xt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(Qr).map(([o,s])=>{let i=xr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>Bx(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>Dx(e)};return[...n,r]}readPluginHooks(e){let n=[xr(e,"hooks","hooks.json"),xr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=Oc(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Mi(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Mi(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=xr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Oc(n,"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(),Be(),Ic(Zx(),".claude"),Ic(Zx(),".config","claude")]));for(let n of e){let r=Ic(n,"plugins","cache","context-mode","context-mode");try{let s=QI(r).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 n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(f=>{let m=f;if(!Hx(m))return!0;let h=m.hooks??[];return h.every(y=>!y.command||!_p(y.command))?!0:h.every(y=>{let _=y.command?_p(y.command):null;return _?Bx(_):!0})}),p=l.length-d.length;p>0&&(r[u]=d,o.push(`Removed ${p} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&zx.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(Qr),d=p=>p!=null&&(l.some(f=>p.includes(f))||p.includes("context-mode hook"));for(let p of Object.keys(r)){let f=r[p];if(!Array.isArray(f))continue;let m=0;for(let g of f){let y=g,_=y.hooks??[],b=_.length;y.hooks=_.filter(v=>!d(v.command)),m+=b-y.hooks.length}let h=f.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(m>0||h.length!==f.length)&&(r[p]=h,m>0&&o.push(`Removed ${m} duplicate ${p} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Xt.PRE_TOOL_USE,Xt.SESSION_START];for(let u of c){let l=yp(u,e);if(u===Xt.PRE_TOOL_USE){let d={matcher:Lx,hooks:[{type:"command",command:l}]},p=r.PreToolUse;if(p&&Array.isArray(p)){let f=p.findIndex(m=>Mi(m,u));f>=0?(p[f]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=p}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},p=r[u];if(p&&Array.isArray(p)){let f=p.findIndex(m=>Mi(m,u));f>=0?(p[f]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r[u]=p}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(Qr)){let o=Ic(e,"hooks",r);try{tA(o,rA.R_OK),eA(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=xr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Oc(r,"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=n,a.lastUpdated=new Date().toISOString();Fx(r,JSON.stringify(o,null,2)+` +`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function Sr(t,e){let n=Ac[t];return e&&n?qe(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var xe,qx,Ac,AW,NW,Vx=x(()=>{"use strict";Pn();xe={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",AFTER_MODEL:"AfterModel",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},qx="mcp__(?!.*context-mode)",Ac={[xe.BEFORE_AGENT]:"beforeagent.mjs",[xe.BEFORE_TOOL]:"beforetool.mjs",[xe.AFTER_TOOL]:"aftertool.mjs",[xe.AFTER_MODEL]:"aftermodel.mjs",[xe.PRE_COMPRESS]:"precompress.mjs",[xe.SESSION_START]:"sessionstart.mjs"},AW=[xe.BEFORE_TOOL,xe.SESSION_START],NW=[xe.AFTER_TOOL,xe.AFTER_MODEL,xe.PRE_COMPRESS]});var Gx={};ye(Gx,{GeminiCLIAdapter:()=>kp});import{readFileSync as Sp,writeFileSync as Wx,mkdirSync as oA,accessSync as sA,chmodSync as iA,existsSync as aA,constants as cA}from"node:fs";import{resolve as Di,join as Kx}from"node:path";import{homedir as Nc}from"node:os";var kp,Jx=x(()=>{"use strict";st();Vx();kp=class extends _e{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 Di(Nc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[xe.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:Sr(xe.BEFORE_AGENT,e)}]}],[xe.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|${qx}`,hooks:[{type:"command",command:Sr(xe.BEFORE_TOOL,e)}]}],[xe.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:Sr(xe.AFTER_TOOL,e)}]}],[xe.AFTER_MODEL]:[{matcher:"",hooks:[{type:"command",command:Sr(xe.AFTER_MODEL,e)}]}],[xe.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:Sr(xe.PRE_COMPRESS,e)}]}],[xe.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:Sr(xe.SESSION_START,e)}]}]}}readSettings(){try{let e=Sp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Di(Nc(),".gemini");oA(n,{recursive:!0}),Wx(this.getSettingsPath(),JSON.stringify(e,null,2)+` +`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[xe.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[xe.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(Ac).map(([n,r])=>{let o=Kx(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>aA(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 n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).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=Di(Nc(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(Sp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:xe.BEFORE_AGENT},{name:xe.BEFORE_TOOL},{name:xe.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:Sr(i.name,e)}]},u=r[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(f=>f.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`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=Kx(e,"hooks","gemini-cli");for(let o of Object.values(Ac)){let s=Di(r,o);try{sA(s,cA.R_OK),iA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Di(Nc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Sp(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),Wx(r,JSON.stringify(o,null,2)+` +`,"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}`}}});function ji(t){let e="",n=!1,r=!1,o=!1;for(let c=0;c{"use strict"});var eo,yW,_W,Ux=x(()=>{"use strict";eo={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},yW=[eo.BEFORE,eo.AFTER],_W=[eo.COMPACTING]});var Bx={};_e(Bx,{OpenCodeAdapter:()=>_p});import{readFileSync as Fx,writeFileSync as VI,mkdirSync as WI,copyFileSync as KI,accessSync as GI,existsSync as JI,constants as XI}from"node:fs";import{resolve as Ut,join as Kn}from"node:path";import{homedir as kr}from"node:os";var _p,Zx=x(()=>{"use strict";it();Di();Ux();_p=class extends ve{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 n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Ut(`${this.platform}.jsonc`);return JI(e)?e:Ut(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ut("kilo.jsonc"),Ut("kilo.json"),Ut(".kilo","kilo.jsonc"),Ut(".kilo","kilo.json"),Ut(".kilocode","kilo.jsonc"),Ut(".kilocode","kilo.json"),Kn(kr(),".config","kilo","kilo.jsonc"),Kn(kr(),".config","kilo","kilo.json")]:[Ut("opencode.jsonc"),Ut("opencode.json"),Ut(".opencode","opencode.jsonc"),Ut(".opencode","opencode.json"),Kn(kr(),".config","opencode","opencode.jsonc"),Kn(kr(),".config","opencode","opencode.json")]}getSessionDir(){let e=ht(),n=e?Kn(e,"context-mode","sessions"):Kn(this.getConfigDir(),"context-mode","sessions");return WI(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Kn(kr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Kn(kr(),".config"),Kn(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[eo.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[eo.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[eo.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(kr()))),r=null,o;for(let s of e)try{let i=Fx(s,"utf-8"),a=s.endsWith(".jsonc")?Mi(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){VI(this.getSettingsPath(),JSON.stringify(e,null,2)+` -`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)?n.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"}):n.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(r)&&n.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)"}),n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),n}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=Ut(kr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(Fx(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=n.plugin??[];o.some(i=>i.includes("context-mode"))?r.push("context-mode already in plugin array"):(o.push("context-mode"),r.push("Added context-mode to plugin array")),n.plugin=o;let s=n.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{GI(this.settingsPath,XI.R_OK);let n=this.settingsPath+".bak";return KI(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){let n=e.plugin;return Array.isArray(n)&&n.some(r=>typeof r=="string"&&r.includes("context-mode"))}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var to,TW,$W,qx=x(()=>{"use strict";to={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},TW=[to.TOOL_CALL_BEFORE,to.TOOL_CALL_AFTER],$W=[to.COMMAND_NEW]});var Vx={};_e(Vx,{OpenClawAdapter:()=>vp});import{readFileSync as bp,writeFileSync as YI,copyFileSync as QI,accessSync as eA,constants as tA}from"node:fs";import{resolve as Gn,join as xp}from"node:path";import{homedir as Sp}from"node:os";var vp,Wx=x(()=>{"use strict";it();qx();vp=class extends ve{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 n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Gn("openclaw.json")}getConfigDir(e){return Gn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return xp(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[to.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Gn("openclaw.json"),Gn(".openclaw","openclaw.json"),xp(Sp(),".openclaw","openclaw.json")];for(let n of e)try{let r=bp(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Gn("openclaw.json");YI(n,JSON.stringify(e,null,2)+` -`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.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;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).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=Gn(Sp(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(bp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Gn("node_modules","context-mode","package.json"),n=JSON.parse(bp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[Gn("openclaw.json"),Gn(".openclaw","openclaw.json"),xp(Sp(),".openclaw","openclaw.json")];for(let n of e)try{eA(n,tA.R_OK);let r=n+".bak";return QI(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}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 Kx}from"node:os";import{resolve as kp}from"node:path";function Gx(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?kp(Kx(),t.replace(/^~[/\\]?/,"")):kp(t):kp(Kx(),".codex")}var Jx=x(()=>{"use strict"});var oS={};_e(oS,{CodexAdapter:()=>Tp,parseCodexContextModePluginRoot:()=>Ac,probeCodexCliVersion:()=>nS});import{execFileSync as tS}from"node:child_process";import{existsSync as nA,readFileSync as fs,writeFileSync as Xx,accessSync as rA,copyFileSync as oA,constants as sA,mkdirSync as wp}from"node:fs";import{resolve as Ic,dirname as Ep,join as Jn}from"node:path";import{fileURLToPath as iA}from"node:url";function nS(t=tS){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function Ac(t){for(let e of t.split(/\r?\n/)){let n=e.match(/^\s*context-mode@context-mode\s+installed,\s+enabled\s+\S+\s+(.+?)\s*$/);if(n?.[1])return n[1].trim()}return null}function Nc(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(` -`):null}function rS(t){let e=Nc(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function uA(t){let e=Nc(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Yx(t){let e=Nc(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Qx(t){return Nc(t,"mcp_servers.context-mode")!==null}function lA(t){if(rS(t))return{text:t,changed:!1};let e=t.includes(`\r +`);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function Wn(t){for(let e of[t,ji(t)])try{return JSON.parse(e)}catch{}}var Li=x(()=>{"use strict"});var eo,FW,BW,Xx=x(()=>{"use strict";eo={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},FW=[eo.BEFORE,eo.AFTER],BW=[eo.COMPACTING]});var Qx={};ye(Qx,{OpenCodeAdapter:()=>wp});import{readFileSync as Yx,writeFileSync as uA,mkdirSync as lA,copyFileSync as dA,accessSync as pA,existsSync as mA,constants as fA}from"node:fs";import{resolve as Ft,join as Kn}from"node:path";import{homedir as kr}from"node:os";var wp,ev=x(()=>{"use strict";st();Li();Xx();wp=class extends _e{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 n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Ft(`${this.platform}.jsonc`);return mA(e)?e:Ft(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ft("kilo.jsonc"),Ft("kilo.json"),Ft(".kilo","kilo.jsonc"),Ft(".kilo","kilo.json"),Ft(".kilocode","kilo.jsonc"),Ft(".kilocode","kilo.json"),Kn(kr(),".config","kilo","kilo.jsonc"),Kn(kr(),".config","kilo","kilo.json")]:[Ft("opencode.jsonc"),Ft("opencode.json"),Ft(".opencode","opencode.jsonc"),Ft(".opencode","opencode.json"),Kn(kr(),".config","opencode","opencode.jsonc"),Kn(kr(),".config","opencode","opencode.json")]}getSessionDir(){let e=et(),n=e?Kn(e,"context-mode","sessions"):Kn(this.getConfigDir(),"context-mode","sessions");return lA(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Kn(kr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Kn(kr(),".config"),Kn(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[eo.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[eo.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[eo.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(kr()))),r=null,o;for(let s of e)try{let i=Yx(s,"utf-8"),a=s.endsWith(".jsonc")?ji(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){uA(this.getSettingsPath(),JSON.stringify(e,null,2)+` +`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)?n.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"}):n.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(r)&&n.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)"}),n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),n}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=Ft(kr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(Yx(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=n.plugin??[];o.some(i=>i.includes("context-mode"))?r.push("context-mode already in plugin array"):(o.push("context-mode"),r.push("Added context-mode to plugin array")),n.plugin=o;let s=n.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{pA(this.settingsPath,fA.R_OK);let n=this.settingsPath+".bak";return dA(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){let n=e.plugin;return Array.isArray(n)&&n.some(r=>typeof r=="string"&&r.includes("context-mode"))}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var to,XW,YW,tv=x(()=>{"use strict";to={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},XW=[to.TOOL_CALL_BEFORE,to.TOOL_CALL_AFTER],YW=[to.COMMAND_NEW]});var nv={};ye(nv,{OpenClawAdapter:()=>Pp});import{readFileSync as Ep,writeFileSync as hA,copyFileSync as gA,accessSync as yA,constants as _A}from"node:fs";import{resolve as Gn,join as Tp}from"node:path";import{homedir as $p}from"node:os";var Pp,rv=x(()=>{"use strict";st();tv();Pp=class extends _e{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 n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Gn("openclaw.json")}getConfigDir(e){return Gn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Tp(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[to.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Gn("openclaw.json"),Gn(".openclaw","openclaw.json"),Tp($p(),".openclaw","openclaw.json")];for(let n of e)try{let r=Ep(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Gn("openclaw.json");hA(n,JSON.stringify(e,null,2)+` +`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.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;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).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=Gn($p(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(Ep(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Gn("node_modules","context-mode","package.json"),n=JSON.parse(Ep(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[Gn("openclaw.json"),Gn(".openclaw","openclaw.json"),Tp($p(),".openclaw","openclaw.json")];for(let n of e)try{yA(n,_A.R_OK);let r=n+".bak";return gA(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}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 ov}from"node:os";import{resolve as Rp}from"node:path";function sv(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Rp(ov(),t.replace(/^~[/\\]?/,"")):Rp(t):Rp(ov(),".codex")}var iv=x(()=>{"use strict"});var fv={};ye(fv,{CodexAdapter:()=>Ip,parseCodexContextModePluginRoot:()=>Dc,probeCodexCliVersion:()=>pv});import{execFileSync as dv}from"node:child_process";import{existsSync as bA,readFileSync as gs,writeFileSync as av,accessSync as xA,copyFileSync as vA,constants as SA,mkdirSync as Cp}from"node:fs";import{resolve as Mc,dirname as Op,join as Jn}from"node:path";import{fileURLToPath as kA}from"node:url";function pv(t=dv){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function Dc(t){for(let e of t.split(/\r?\n/)){let n=e.match(/^\s*context-mode@context-mode\s+installed,\s+enabled\s+\S+\s+(.+?)\s*$/);if(n?.[1])return n[1].trim()}return null}function jc(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(` +`):null}function mv(t){let e=jc(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function TA(t){let e=jc(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function cv(t){let e=jc(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function uv(t){return jc(t,"mcp_servers.context-mode")!==null}function $A(t){if(mv(t))return{text:t,changed:!1};let e=t.includes(`\r `)?`\r `:` `,n=t.split(/\r?\n/),r=n.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(r===-1){let s=t.length>0&&!t.endsWith(` -`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s{"use strict";it();Jt();Jx();aA="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__",no={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"},cA={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"]};Tp=class extends ve{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??tS}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 Gx()}getSettingsPath(){return Jn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=ht(),n=e?Jn(e,"context-mode","sessions"):Jn(this.getConfigDir(),"context-mode","sessions");return wp(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=ht(),r=n?Jn(n,"context-mode","memories"):Jn(this.getConfigDir(),"memories");return e?Jn(r,rt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:aA,hooks:[{type:"command",command:no.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:no.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:no.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:no.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:no.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:no.Stop}]}]}}readSettings(){try{return{_raw_toml:fs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=nS(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=fs(this.getSettingsPath(),"utf-8"),s=!0;let f=rS(o),m=!f&&uA(o);n.push({check:"Codex hooks feature flag",status:f?"pass":"fail",message:f?`[features].hooks enabled in ${this.getSettingsPath()}`:m?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...f?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:"context-mode@context-mode is enabled, but `codex plugin list` did not report its runtime root",fix:"Restart Codex or verify `codex plugin list` shows context-mode@context-mode installed and enabled"}),c&&!u){let f=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Jn(f,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&Qx(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let f=Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by context-mode@context-mode plugin`}));return n.concat(f)}return l.reason==="missing"?n.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"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.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 d=u?Object.keys(i).map(f=>({check:`${f} hook`,status:"pass",message:`${f} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([f,m])=>{let h=l.config.hooks?.[f],g=m[0],y=Array.isArray(h)&&h.some(b=>this.isExpectedHookEntry(f,b,g)),_=f==="PreCompact"?"warn":"fail";return{check:`${f} hook`,status:y?"pass":_,message:y?`${f} hook configured in ${this.getHooksPath()}`:f==="PreCompact"?`${f} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${f} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),p=[];for(let f of Object.keys(i)){let m=l.config.hooks?.[f];if(!Array.isArray(m))continue;let h=m.filter(g=>this.isManagedContextModeEntry(f,g)).length;h>1?p.push({check:`${f} duplicates`,status:"warn",message:`${h} context-mode entries found for ${f} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&h===1&&p.push({check:`${f} plugin duplicate`,status:"warn",message:`${f} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return n.concat(d,p)}checkPluginRegistration(){try{let e=fs(this.getSettingsPath(),"utf-8"),n=Yx(e),r=Qx(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:r?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{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 n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=fs(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let m=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${m}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let m of Object.keys(l))this.removeManagedHookEntries(u,m,r);else for(let[m,h]of Object.entries(l))this.upsertManagedHookEntry(u,m,h[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let p=lA(s).text,f=p!==s;if(a){let m=eS(p,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));m.removed.length>0&&(p=m.text,r.push("Removed standalone Codex context-mode MCP registration"));let h=this.pruneStaleUserHookTrustState(p,u);h.removed.length>0&&(p=h.text,r.push(`Removed ${h.removed.length} stale Codex hook trust entr${h.removed.length===1?"y":"ies"}`))}if(p!==s){let m=p.includes(`\r +`,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(n),removed:s}}function PA(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var wA,no,EA,Ip,Ap=x(()=>{"use strict";st();Ut();iv();wA="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__",no={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"},EA={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"]};Ip=class extends _e{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??dv}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 sv()}getSettingsPath(){return Jn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=et(),n=e?Jn(e,"context-mode","sessions"):Jn(this.getConfigDir(),"context-mode","sessions");return Cp(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=et(),r=n?Jn(n,"context-mode","memories"):Jn(this.getConfigDir(),"memories");return e?Jn(r,Ge(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:wA,hooks:[{type:"command",command:no.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:no.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:no.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:no.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:no.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:no.Stop}]}]}}readSettings(){try{return{_raw_toml:gs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=pv(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=gs(this.getSettingsPath(),"utf-8"),s=!0;let f=mv(o),m=!f&&TA(o);n.push({check:"Codex hooks feature flag",status:f?"pass":"fail",message:f?`[features].hooks enabled in ${this.getSettingsPath()}`:m?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...f?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:"context-mode@context-mode is enabled, but `codex plugin list` did not report its runtime root",fix:"Restart Codex or verify `codex plugin list` shows context-mode@context-mode installed and enabled"}),c&&!u){let f=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Jn(f,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&uv(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let f=Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by context-mode@context-mode plugin`}));return n.concat(f)}return l.reason==="missing"?n.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"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.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 d=u?Object.keys(i).map(f=>({check:`${f} hook`,status:"pass",message:`${f} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([f,m])=>{let h=l.config.hooks?.[f],g=m[0],y=Array.isArray(h)&&h.some(b=>this.isExpectedHookEntry(f,b,g)),_=f==="PreCompact"?"warn":"fail";return{check:`${f} hook`,status:y?"pass":_,message:y?`${f} hook configured in ${this.getHooksPath()}`:f==="PreCompact"?`${f} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${f} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),p=[];for(let f of Object.keys(i)){let m=l.config.hooks?.[f];if(!Array.isArray(m))continue;let h=m.filter(g=>this.isManagedContextModeEntry(f,g)).length;h>1?p.push({check:`${f} duplicates`,status:"warn",message:`${h} context-mode entries found for ${f} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&h===1&&p.push({check:`${f} plugin duplicate`,status:"warn",message:`${f} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return n.concat(d,p)}checkPluginRegistration(){try{let e=gs(this.getSettingsPath(),"utf-8"),n=cv(e),r=uv(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:r?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{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 n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=gs(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let m=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${m}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let m of Object.keys(l))this.removeManagedHookEntries(u,m,r);else for(let[m,h]of Object.entries(l))this.upsertManagedHookEntry(u,m,h[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let p=$A(s).text,f=p!==s;if(a){let m=lv(p,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));m.removed.length>0&&(p=m.text,r.push("Removed standalone Codex context-mode MCP registration"));let h=this.pruneStaleUserHookTrustState(p,u);h.removed.length>0&&(p=h.text,r.push(`Removed ${h.removed.length} stale Codex hook trust entr${h.removed.length===1?"y":"ies"}`))}if(p!==s){let m=p.includes(`\r `)?`\r `:` `,h=p.endsWith(` -`)?p:`${p}${m}`;wp(Ep(o),{recursive:!0}),Xx(o,h,"utf-8"),f&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{rA(n,sA.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Ic(Ep(iA(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return fs(e,"utf-8")}catch{return`# context-mode +`)?p:`${p}${m}`;Cp(Op(o),{recursive:!0}),av(o,h,"utf-8"),f&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{xA(n,SA.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Mc(Op(kA(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return gs(e,"utf-8")}catch{return`# context-mode -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 Jn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return oA(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(fs(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();wp(Ep(n),{recursive:!0}),Xx(n,JSON.stringify(e,null,2)+` -`,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return nA(Jn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&Yx(n),s=Ic(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return Ac(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(Ic(e))===this.normalizeCommand(Ic(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return eS(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=dA(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),p=o[u.pop()??""];if(u.join(":")!==r||!p||!Number.isInteger(d)||!Number.isInteger(l))return!1;let m=n[p]?.[d];return!m||!Array.isArray(m.hooks)||!m.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(no[e]??""),s=cA[e]??[];return r.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 sS,writeFileSync as pA,mkdirSync as mA,accessSync as fA,chmodSync as hA,constants as gA}from"node:fs";import{resolve as Mc,join as yA}from"node:path";var wr,Dc=x(()=>{"use strict";it();wr=class extends ve{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=sS(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=sS(Mc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();mA(Mc(".github","hooks"),{recursive:!0}),pA(n,JSON.stringify(e,null,2)+` -`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.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)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=yA(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Mc(r,o);try{fA(s,gA.R_OK),hA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function iS(t,e){if(!Pp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,Pp,KW,GW,aS=x(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Pp={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},KW=[Yt.PRE_TOOL_USE,Yt.SESSION_START],GW=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var uS={};_e(uS,{VSCodeCopilotAdapter:()=>Op});import{readFileSync as Rp,mkdirSync as cS,accessSync as _A,existsSync as bA,constants as xA}from"node:fs";import{resolve as hs,join as ji}from"node:path";import{homedir as Cp}from"node:os";var Op,lS=x(()=>{"use strict";Dc();it();aS();Op=class extends wr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:Pp,buildHookCommand:iS};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=ht();if(e){let s=ji(e,"context-mode","sessions");return cS(s,{recursive:!0}),s}let n=hs(".github","context-mode","sessions"),r=ji(Cp(),".vscode","context-mode","sessions"),o=bA(hs(".github"))?n:r;return cS(o,{recursive:!0}),o}getConfigDir(e){return hs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=hs(".github","hooks");try{_A(r,xA.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=hs(r,"context-mode.json");try{let s=Rp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=hs(".vscode","mcp.json"),n=Rp(e,"utf-8"),o=JSON.parse(n).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=[ji(Cp(),".vscode","extensions"),ji(Cp(),".vscode-insiders","extensions")];for(let n of e)try{let r=Rp(ji(n,"extensions.json"),"utf-8"),s=JSON.parse(r).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 dS(t,e){if(!Ip[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,Ip,r3,o3,pS=x(()=>{"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"},Ip={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},r3=[Qt.PRE_TOOL_USE,Qt.SESSION_START],o3=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var mS={};_e(mS,{JetBrainsCopilotAdapter:()=>Ap});import{readFileSync as SA}from"node:fs";import{resolve as vA}from"node:path";var Ap,fS=x(()=>{"use strict";Dc();pS();Ap=class extends wr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:Ip,buildHookCommand:dS};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 vA(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=SA(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[Qt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}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 n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function hS(t,e){let n=Np[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var St,Np,d3,p3,gS=x(()=>{"use strict";St={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Np={[St.PRE_TOOL_USE]:"pretooluse.mjs",[St.POST_TOOL_USE]:"posttooluse.mjs",[St.PRE_COMPACT]:"precompact.mjs",[St.SESSION_START]:"sessionstart.mjs",[St.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[St.STOP]:"stop.mjs"},d3=[St.PRE_TOOL_USE,St.SESSION_START],p3=[St.POST_TOOL_USE,St.PRE_COMPACT,St.USER_PROMPT_SUBMIT,St.STOP]});var vS={};_e(vS,{CopilotCliAdapter:()=>Dp,copilotCliHome:()=>Lc,copilotCliMcpConfigPath:()=>jc});import{existsSync as yS,mkdirSync as _S,readFileSync as Mp,writeFileSync as kA}from"node:fs";import{homedir as bS}from"node:os";import{dirname as wA,join as gs,resolve as SS}from"node:path";function xS(){return process.env[EA]==="1"}function TA(t){return SS(t,"configs","copilot-cli","hooks.json")}function $A(t){return Wn(Mp(t,"utf-8"))??{}}function PA(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function Lc(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?gs(bS(),t.replace(/^~[/\\]?/,"")):SS(t):gs(bS(),".copilot")}function jc(){return gs(Lc(),"mcp-config.json")}var EA,Dp,kS=x(()=>{"use strict";Dc();it();Di();gS();EA="CONTEXT_MODE_COPILOT_PLUGIN";Dp=class extends wr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:St,HOOK_SCRIPTS:Np,buildHookCommand:hS};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return gs(Lc(),"hooks","context-mode.json")}getConfigDir(e){return Lc()}getSessionDir(){let e=ht(),n=e?gs(e,"context-mode","sessions"):gs(this.getConfigDir(),"context-mode","sessions");return _S(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();_S(wA(n),{recursive:!0}),kA(n,JSON.stringify(e,null,2)+` -`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=Mp(this.getSettingsPath(),"utf-8");return Wn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=xS(),o=r?TA(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=$A(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(St)){let l=PA(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(xS())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=Mp(jc(),"utf-8");return"context-mode"in((Wn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${jc()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return yS(jc())||yS(this.getSettingsPath())?"standalone":"not installed"}}});function Li(t,e){let n=jp[e],r=en(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function en(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ke,jp,RA,CA,Lp,wS,ES,TS=x(()=>{"use strict";ke={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},jp={[ke.PRE_TOOL_USE]:"pretooluse.mjs",[ke.POST_TOOL_USE]:"posttooluse.mjs",[ke.SESSION_START]:"sessionstart.mjs",[ke.STOP]:"stop.mjs",[ke.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},RA="MCP:(?!ctx_)",CA=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",RA],Lp=CA.join("|"),wS=[ke.PRE_TOOL_USE],ES=[ke.POST_TOOL_USE]});var OS={};_e(OS,{CursorAdapter:()=>zp});import{readFileSync as zc,writeFileSync as OA,mkdirSync as IA,accessSync as $S,chmodSync as AA,constants as PS,existsSync as RS,readdirSync as NA}from"node:fs";import{execSync as MA}from"node:child_process";import{resolve as ro,join as oo}from"node:path";import{homedir as Hc}from"node:os";var CS,zp,IS=x(()=>{"use strict";it();Sr();TS();CS="/Library/Application Support/Cursor/hooks.json",zp=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return ro(".cursor","hooks.json")}getConfigDir(e){return ro(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ke.PRE_TOOL_USE]:[{type:"command",command:en(ke.PRE_TOOL_USE),matcher:Lp,loop_limit:null,failClosed:!1}],[ke.POST_TOOL_USE]:[{type:"command",command:en(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ke.SESSION_START]:[{type:"command",command:en(ke.SESSION_START),loop_limit:null,failClosed:!1}],[ke.STOP]:[{type:"command",command:en(ke.STOP),loop_limit:null,failClosed:!1}],[ke.AFTER_AGENT_RESPONSE]:[{type:"command",command:en(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=zc(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();IA(ro(".cursor"),{recursive:!0}),OA(n,JSON.stringify(e,null,2)+` -`,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.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=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of wS){let a=s[i],c=Array.isArray(a)&&a.some(u=>Li(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of ES){let a=s[i],c=Array.isArray(a)&&a.some(u=>Li(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}RS(CS)&&n.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()&&n.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&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Li(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.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"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[oo(Hc(),".cursor","plugins","local"),oo(Hc(),".cursor","plugins","cache")],n=[];for(let r of e){try{$S(r,PS.F_OK)}catch{continue}let o=[];try{o=NA(r)}catch{continue}for(let s of o){let i=oo(r,s,".cursor-plugin","plugin.json");try{let a=zc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[ro(".cursor","mcp.json"),oo(Hc(),".cursor","mcp.json")];for(let r of e)try{let o=zc(r,"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 ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return MA("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,ke.PRE_TOOL_USE,{type:"command",command:en(ke.PRE_TOOL_USE),matcher:Lp,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.POST_TOOL_USE,{type:"command",command:en(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.SESSION_START,{type:"command",command:en(ke.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.STOP,{type:"command",command:en(ke.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.AFTER_AGENT_RESPONSE,{type:"command",command:en(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=oo(e,"hooks","cursor");for(let o of Object.values(jp)){let s=ro(r,o);try{$S(s,PS.R_OK),AA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),oo(Hc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(CS),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 n=zc(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[ro(".claude","settings.json"),ro(".claude","settings.local.json"),oo(Be(),"settings.json")].some(n=>RS(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Li(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var NS={};_e(NS,{AntigravityAdapter:()=>zi});import{readFileSync as Uc,writeFileSync as DA,mkdirSync as jA}from"node:fs";import{resolve as Fc,dirname as AS}from"node:path";import{fileURLToPath as LA}from"node:url";import{homedir as Hp}from"node:os";var zi,Up=x(()=>{"use strict";it();zi=class extends ve{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 Fc(Hp(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Fc(Hp(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Uc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();jA(AS(n),{recursive:!0}),DA(n,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=Uc(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=Fc(Hp(),".gemini","extensions","context-mode","package.json");return JSON.parse(Uc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Fc(AS(LA(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Uc(e,"utf-8")}catch{return`# context-mode +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 Jn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return vA(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(gs(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();Cp(Op(n),{recursive:!0}),av(n,JSON.stringify(e,null,2)+` +`,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return bA(Jn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&cv(n),s=Mc(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return Dc(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(Mc(e))===this.normalizeCommand(Mc(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return lv(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=PA(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),p=o[u.pop()??""];if(u.join(":")!==r||!p||!Number.isInteger(d)||!Number.isInteger(l))return!1;let m=n[p]?.[d];return!m||!Array.isArray(m.hooks)||!m.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(no[e]??""),s=EA[e]??[];return r.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 hv,writeFileSync as RA,mkdirSync as CA,accessSync as OA,chmodSync as IA,constants as AA}from"node:fs";import{resolve as Lc,join as NA}from"node:path";var wr,zc=x(()=>{"use strict";st();wr=class extends _e{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 Lc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=hv(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=hv(Lc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();CA(Lc(".github","hooks"),{recursive:!0}),RA(n,JSON.stringify(e,null,2)+` +`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.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)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=NA(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Lc(r,o);try{OA(s,AA.R_OK),IA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function gv(t,e){if(!Np[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,Np,b3,x3,yv=x(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Np={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},b3=[Yt.PRE_TOOL_USE,Yt.SESSION_START],x3=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var bv={};ye(bv,{VSCodeCopilotAdapter:()=>jp});import{readFileSync as Mp,mkdirSync as _v,accessSync as MA,existsSync as DA,constants as jA}from"node:fs";import{resolve as ys,join as zi}from"node:path";import{homedir as Dp}from"node:os";var jp,xv=x(()=>{"use strict";zc();st();yv();jp=class extends wr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:Np,buildHookCommand:gv};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=et();if(e){let s=zi(e,"context-mode","sessions");return _v(s,{recursive:!0}),s}let n=ys(".github","context-mode","sessions"),r=zi(Dp(),".vscode","context-mode","sessions"),o=DA(ys(".github"))?n:r;return _v(o,{recursive:!0}),o}getConfigDir(e){return ys(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=ys(".github","hooks");try{MA(r,jA.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=ys(r,"context-mode.json");try{let s=Mp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=ys(".vscode","mcp.json"),n=Mp(e,"utf-8"),o=JSON.parse(n).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=[zi(Dp(),".vscode","extensions"),zi(Dp(),".vscode-insiders","extensions")];for(let n of e)try{let r=Mp(zi(n,"extensions.json"),"utf-8"),s=JSON.parse(r).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 vv(t,e){if(!Lp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,Lp,P3,R3,Sv=x(()=>{"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"},Lp={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},P3=[Qt.PRE_TOOL_USE,Qt.SESSION_START],R3=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var kv={};ye(kv,{JetBrainsCopilotAdapter:()=>zp});import{readFileSync as LA}from"node:fs";import{resolve as zA}from"node:path";var zp,wv=x(()=>{"use strict";zc();Sv();zp=class extends wr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:Lp,buildHookCommand:vv};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 zA(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=LA(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[Qt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}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 n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function Ev(t,e){let n=Hp[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var vt,Hp,D3,j3,Tv=x(()=>{"use strict";vt={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Hp={[vt.PRE_TOOL_USE]:"pretooluse.mjs",[vt.POST_TOOL_USE]:"posttooluse.mjs",[vt.PRE_COMPACT]:"precompact.mjs",[vt.SESSION_START]:"sessionstart.mjs",[vt.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[vt.STOP]:"stop.mjs"},D3=[vt.PRE_TOOL_USE,vt.SESSION_START],j3=[vt.POST_TOOL_USE,vt.PRE_COMPACT,vt.USER_PROMPT_SUBMIT,vt.STOP]});var Iv={};ye(Iv,{CopilotCliAdapter:()=>Fp,copilotCliHome:()=>Uc,copilotCliMcpConfigPath:()=>Hc});import{existsSync as $v,mkdirSync as Pv,readFileSync as Up,writeFileSync as HA}from"node:fs";import{homedir as Rv}from"node:os";import{dirname as UA,join as _s,resolve as Ov}from"node:path";function Cv(){return process.env[FA]==="1"}function BA(t){return Ov(t,"configs","copilot-cli","hooks.json")}function ZA(t){return Wn(Up(t,"utf-8"))??{}}function qA(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function Uc(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?_s(Rv(),t.replace(/^~[/\\]?/,"")):Ov(t):_s(Rv(),".copilot")}function Hc(){return _s(Uc(),"mcp-config.json")}var FA,Fp,Av=x(()=>{"use strict";zc();st();Li();Tv();FA="CONTEXT_MODE_COPILOT_PLUGIN";Fp=class extends wr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:vt,HOOK_SCRIPTS:Hp,buildHookCommand:Ev};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return _s(Uc(),"hooks","context-mode.json")}getConfigDir(e){return Uc()}getSessionDir(){let e=et(),n=e?_s(e,"context-mode","sessions"):_s(this.getConfigDir(),"context-mode","sessions");return Pv(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();Pv(UA(n),{recursive:!0}),HA(n,JSON.stringify(e,null,2)+` +`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=Up(this.getSettingsPath(),"utf-8");return Wn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=Cv(),o=r?BA(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=ZA(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(vt)){let l=qA(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(Cv())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=Up(Hc(),"utf-8");return"context-mode"in((Wn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${Hc()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return $v(Hc())||$v(this.getSettingsPath())?"standalone":"not installed"}}});function Hi(t,e){let n=Bp[e],r=en(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function en(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ke,Bp,VA,WA,Zp,Nv,Mv,Dv=x(()=>{"use strict";ke={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Bp={[ke.PRE_TOOL_USE]:"pretooluse.mjs",[ke.POST_TOOL_USE]:"posttooluse.mjs",[ke.SESSION_START]:"sessionstart.mjs",[ke.STOP]:"stop.mjs",[ke.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},VA="MCP:(?!ctx_)",WA=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",VA],Zp=WA.join("|"),Nv=[ke.PRE_TOOL_USE],Mv=[ke.POST_TOOL_USE]});var Uv={};ye(Uv,{CursorAdapter:()=>qp});import{readFileSync as Fc,writeFileSync as KA,mkdirSync as GA,accessSync as jv,chmodSync as JA,constants as Lv,existsSync as zv,readdirSync as XA}from"node:fs";import{execSync as YA}from"node:child_process";import{resolve as ro,join as oo}from"node:path";import{homedir as Bc}from"node:os";var Hv,qp,Fv=x(()=>{"use strict";st();vr();Dv();Hv="/Library/Application Support/Cursor/hooks.json",qp=class extends _e{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return ro(".cursor","hooks.json")}getConfigDir(e){return ro(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ke.PRE_TOOL_USE]:[{type:"command",command:en(ke.PRE_TOOL_USE),matcher:Zp,loop_limit:null,failClosed:!1}],[ke.POST_TOOL_USE]:[{type:"command",command:en(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ke.SESSION_START]:[{type:"command",command:en(ke.SESSION_START),loop_limit:null,failClosed:!1}],[ke.STOP]:[{type:"command",command:en(ke.STOP),loop_limit:null,failClosed:!1}],[ke.AFTER_AGENT_RESPONSE]:[{type:"command",command:en(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=Fc(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();GA(ro(".cursor"),{recursive:!0}),KA(n,JSON.stringify(e,null,2)+` +`,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.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=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of Nv){let a=s[i],c=Array.isArray(a)&&a.some(u=>Hi(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of Mv){let a=s[i],c=Array.isArray(a)&&a.some(u=>Hi(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}zv(Hv)&&n.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()&&n.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&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Hi(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.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"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[oo(Bc(),".cursor","plugins","local"),oo(Bc(),".cursor","plugins","cache")],n=[];for(let r of e){try{jv(r,Lv.F_OK)}catch{continue}let o=[];try{o=XA(r)}catch{continue}for(let s of o){let i=oo(r,s,".cursor-plugin","plugin.json");try{let a=Fc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[ro(".cursor","mcp.json"),oo(Bc(),".cursor","mcp.json")];for(let r of e)try{let o=Fc(r,"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 ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return YA("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,ke.PRE_TOOL_USE,{type:"command",command:en(ke.PRE_TOOL_USE),matcher:Zp,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.POST_TOOL_USE,{type:"command",command:en(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.SESSION_START,{type:"command",command:en(ke.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.STOP,{type:"command",command:en(ke.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.AFTER_AGENT_RESPONSE,{type:"command",command:en(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=oo(e,"hooks","cursor");for(let o of Object.values(Bp)){let s=ro(r,o);try{jv(s,Lv.R_OK),JA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),oo(Bc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(Hv),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 n=Fc(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[ro(".claude","settings.json"),ro(".claude","settings.local.json"),oo(Be(),"settings.json")].some(n=>zv(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Hi(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var Zv={};ye(Zv,{AntigravityAdapter:()=>Ui});import{readFileSync as Zc,writeFileSync as QA,mkdirSync as eN}from"node:fs";import{resolve as qc,dirname as Bv}from"node:path";import{fileURLToPath as tN}from"node:url";import{homedir as Vp}from"node:os";var Ui,Wp=x(()=>{"use strict";st();Ui=class extends _e{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 qc(Vp(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return qc(Vp(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Zc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();eN(Bv(n),{recursive:!0}),QA(n,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=Zc(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=qc(Vp(),".gemini","extensions","context-mode","package.json");return JSON.parse(Zc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=qc(Bv(tN(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Zc(e,"utf-8")}catch{return`# context-mode -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 BS={};_e(BS,{AntigravityCliAdapter:()=>Wp,antigravityCliConfigDir:()=>US,antigravityCliHooksPath:()=>Bp,antigravityCliMcpConfigPath:()=>HS,antigravityCliPluginDir:()=>qc});import{mkdirSync as zA,readFileSync as Bc,writeFileSync as HA}from"node:fs";import{dirname as UA,resolve as so}from"node:path";import{homedir as Zc}from"node:os";function HS(){return so(Zc(),".gemini","config","mcp_config.json")}function US(){return so(Zc(),".gemini","antigravity-cli")}function Bp(){return so(Zc(),".gemini","config","hooks.json")}function qc(){return so(Zc(),".gemini","config","plugins","context-mode")}function FA(){return so(qc(),"mcp_config.json")}function BA(){return so(qc(),"hooks.json")}function MS(t){for(let e of t)try{if("context-mode"in((Wn(Bc(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function In(t){return t&&typeof t=="object"?t:{}}function DS(t){let e=In(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function jS(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function FS(t,e){let n=In(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>In(o).command===e)}function LS(t,e){return JSON.stringify(t).includes(e)}function ZA(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function zS(t,e){return Array.isArray(t)&&t.some(n=>FS(n,e))}function qA(t){return Array.isArray(t)&&t.some(e=>{let n=In(e);return ZA(n.matcher)&&FS(e,Zp)})}function VA(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(Wn(Bc(n,"utf-8"))??{}).hooks??{},s=qA(o.PreToolUse),i=zS(o.PostToolUse,qp),a=zS(o.Stop,Vp);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function KA(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function Fp(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!LS(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!LS(a,r)),n],!0)}var Zp,WA,qp,Vp,Wp,ZS=x(()=>{"use strict";Up();Di();Zp="context-mode hook antigravity-cli pretooluse",WA="run_command|view_file|grep_search|web_fetch|read_url_content",qp="context-mode hook antigravity-cli posttooluse",Vp="context-mode hook antigravity-cli stop";Wp=class extends zi{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return HS()}getConfigDir(e){return US()}parsePreToolUseInput(e){let n=In(e),r=In(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:In(r.args),sessionId:jS(n),projectDir:DS(n),raw:e}}parsePostToolUseInput(e){let n=In(e),r=In(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:In(r.args),toolOutput:o,isError:o.length>0,sessionId:jS(n),projectDir:DS(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:KA(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=MS([FA(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}getInstalledVersion(){try{let e=Wn(Bc(so(qc(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return MS([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=Bp(),o={};try{o=Wn(Bc(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:WA,hooks:[{type:"command",command:Zp}]},a={matcher:"",hooks:[{type:"command",command:qp}]},c={matcher:"",hooks:[{type:"command",command:Vp}]},u=Fp(s,"PreToolUse",i,Zp),l=Fp(s,"PostToolUse",a,qp),d=Fp(s,"Stop",c,Vp);return(u||l||d)&&(o.hooks=s,zA(UA(r),{recursive:!0}),HA(r,JSON.stringify(o,null,2)+` -`,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=VA([BA(),Bp()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli\` or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}]}}});function Vc(t,e){let n=qS[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function ys(t,e){let n=qS[t];return e&&n?qe(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var ze,qS,GA,JA,Kp,H3,U3,VS=x(()=>{"use strict";Rn();ze={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},qS={[ze.PRE_TOOL_USE]:"pretooluse.mjs",[ze.POST_TOOL_USE]:"posttooluse.mjs",[ze.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[ze.AGENT_SPAWN]:"agentspawn.mjs"},GA="@(?!context-mode/)",JA=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",GA],Kp=JA.join("|"),H3=[ze.PRE_TOOL_USE,ze.AGENT_SPAWN],U3=[ze.POST_TOOL_USE,ze.USER_PROMPT_SUBMIT]});var JS={};_e(JS,{KiroAdapter:()=>Gp});import{readFileSync as _s,writeFileSync as WS,mkdirSync as KS}from"node:fs";import{resolve as io,dirname as GS}from"node:path";import{fileURLToPath as XA}from"node:url";import{homedir as Wc}from"node:os";var Gp,XS=x(()=>{"use strict";it();VS();Gp=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.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 io(Wc(),".kiro","settings","mcp.json")}getConfigDir(e){return io(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[ze.PRE_TOOL_USE]:[{matcher:Kp,hooks:[{type:"command",command:ys(ze.PRE_TOOL_USE,e)}]}],[ze.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ys(ze.POST_TOOL_USE,e)}]}],[ze.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ys(ze.AGENT_SPAWN,e)}]}],[ze.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ys(ze.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=_s(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();KS(GS(n),{recursive:!0}),WS(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=io(Wc(),".kiro","agents","default.json");try{let s=JSON.parse(_s(r,"utf-8")).hooks??{};for(let i of[ze.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Vc(u,i));n.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[ze.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>Vc(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=_s(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=io(Wc(),".kiro","extensions","context-mode","package.json");return JSON.parse(_s(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=io(Wc(),".kiro","agents"),o=io(r,"default.json");try{KS(r,{recursive:!0});let s={};try{s=JSON.parse(_s(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[ze.PRE_TOOL_USE,Kp],[ze.POST_TOOL_USE,"*"],[ze.AGENT_SPAWN,"*"],[ze.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Vc(d,c))||(l.push({matcher:u,command:ys(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,WS(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=io(GS(XA(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return _s(e,"utf-8")}catch{return`# context-mode +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 Qv={};ye(Qv,{AntigravityCliAdapter:()=>Qp,antigravityCliConfigDir:()=>Xv,antigravityCliHooksPath:()=>Gp,antigravityCliMcpConfigPath:()=>Jv,antigravityCliPluginDir:()=>Kc});import{mkdirSync as nN,readFileSync as Vc,writeFileSync as rN}from"node:fs";import{dirname as oN,resolve as so}from"node:path";import{homedir as Wc}from"node:os";function Jv(){return so(Wc(),".gemini","config","mcp_config.json")}function Xv(){return so(Wc(),".gemini","antigravity-cli")}function Gp(){return so(Wc(),".gemini","config","hooks.json")}function Kc(){return so(Wc(),".gemini","config","plugins","context-mode")}function sN(){return so(Kc(),"mcp_config.json")}function iN(){return so(Kc(),"hooks.json")}function qv(t){for(let e of t)try{if("context-mode"in((Wn(Vc(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function On(t){return t&&typeof t=="object"?t:{}}function Vv(t){let e=On(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function Wv(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function Yv(t,e){let n=On(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>On(o).command===e)}function Kv(t,e){return JSON.stringify(t).includes(e)}function aN(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function Gv(t,e){return Array.isArray(t)&&t.some(n=>Yv(n,e))}function cN(t){return Array.isArray(t)&&t.some(e=>{let n=On(e);return aN(n.matcher)&&Yv(e,Jp)})}function uN(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(Wn(Vc(n,"utf-8"))??{}).hooks??{},s=cN(o.PreToolUse),i=Gv(o.PostToolUse,Xp),a=Gv(o.Stop,Yp);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function dN(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function Kp(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!Kv(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!Kv(a,r)),n],!0)}var Jp,lN,Xp,Yp,Qp,eS=x(()=>{"use strict";Wp();Li();Jp="context-mode hook antigravity-cli pretooluse",lN="run_command|view_file|grep_search|web_fetch|read_url_content",Xp="context-mode hook antigravity-cli posttooluse",Yp="context-mode hook antigravity-cli stop";Qp=class extends Ui{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return Jv()}getConfigDir(e){return Xv()}parsePreToolUseInput(e){let n=On(e),r=On(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:On(r.args),sessionId:Wv(n),projectDir:Vv(n),raw:e}}parsePostToolUseInput(e){let n=On(e),r=On(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:On(r.args),toolOutput:o,isError:o.length>0,sessionId:Wv(n),projectDir:Vv(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:dN(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=qv([sN(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}getInstalledVersion(){try{let e=Wn(Vc(so(Kc(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return qv([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=Gp(),o={};try{o=Wn(Vc(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:lN,hooks:[{type:"command",command:Jp}]},a={matcher:"",hooks:[{type:"command",command:Xp}]},c={matcher:"",hooks:[{type:"command",command:Yp}]},u=Kp(s,"PreToolUse",i,Jp),l=Kp(s,"PostToolUse",a,Xp),d=Kp(s,"Stop",c,Yp);return(u||l||d)&&(o.hooks=s,nN(oN(r),{recursive:!0}),rN(r,JSON.stringify(o,null,2)+` +`,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=uN([iN(),Gp()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli\` or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}]}}});function Gc(t,e){let n=tS[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function bs(t,e){let n=tS[t];return e&&n?qe(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var He,tS,pN,mN,em,dK,pK,nS=x(()=>{"use strict";Pn();He={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},tS={[He.PRE_TOOL_USE]:"pretooluse.mjs",[He.POST_TOOL_USE]:"posttooluse.mjs",[He.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[He.AGENT_SPAWN]:"agentspawn.mjs"},pN="@(?!context-mode/)",mN=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",pN],em=mN.join("|"),dK=[He.PRE_TOOL_USE,He.AGENT_SPAWN],pK=[He.POST_TOOL_USE,He.USER_PROMPT_SUBMIT]});var iS={};ye(iS,{KiroAdapter:()=>tm});import{readFileSync as xs,writeFileSync as rS,mkdirSync as oS}from"node:fs";import{resolve as io,dirname as sS}from"node:path";import{fileURLToPath as fN}from"node:url";import{homedir as Jc}from"node:os";var tm,aS=x(()=>{"use strict";st();nS();tm=class extends _e{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.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 io(Jc(),".kiro","settings","mcp.json")}getConfigDir(e){return io(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[He.PRE_TOOL_USE]:[{matcher:em,hooks:[{type:"command",command:bs(He.PRE_TOOL_USE,e)}]}],[He.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:bs(He.POST_TOOL_USE,e)}]}],[He.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:bs(He.AGENT_SPAWN,e)}]}],[He.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:bs(He.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=xs(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();oS(sS(n),{recursive:!0}),rS(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=io(Jc(),".kiro","agents","default.json");try{let s=JSON.parse(xs(r,"utf-8")).hooks??{};for(let i of[He.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Gc(u,i));n.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=>Gc(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=xs(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=io(Jc(),".kiro","extensions","context-mode","package.json");return JSON.parse(xs(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=io(Jc(),".kiro","agents"),o=io(r,"default.json");try{oS(r,{recursive:!0});let s={};try{s=JSON.parse(xs(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[He.PRE_TOOL_USE,em],[He.POST_TOOL_USE,"*"],[He.AGENT_SPAWN,"*"],[He.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Gc(d,c))||(l.push({matcher:u,command:bs(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,rS(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=io(sS(fN(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return xs(e,"utf-8")}catch{return`# context-mode -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 ev={};_e(ev,{ZedAdapter:()=>Xp});import{readFileSync as Jp,writeFileSync as YA,mkdirSync as QA}from"node:fs";import{resolve as YS,dirname as QS}from"node:path";import{fileURLToPath as eN}from"node:url";import{homedir as tN}from"node:os";var Xp,tv=x(()=>{"use strict";it();Xp=class extends ve{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 YS(tN(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Jp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();QA(QS(n),{recursive:!0}),YA(n,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=Jp(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{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,n){}getRoutingInstructions(){let e=YS(QS(eN(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Jp(e,"utf-8")}catch{return`# context-mode +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 lS={};ye(lS,{ZedAdapter:()=>rm});import{readFileSync as nm,writeFileSync as hN,mkdirSync as gN}from"node:fs";import{resolve as cS,dirname as uS}from"node:path";import{fileURLToPath as yN}from"node:url";import{homedir as _N}from"node:os";var rm,dS=x(()=>{"use strict";st();rm=class extends _e{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 cS(_N(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=nm(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();gN(uS(n),{recursive:!0}),hN(n,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=nm(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{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,n){}getRoutingInstructions(){let e=cS(uS(yN(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return nm(e,"utf-8")}catch{return`# context-mode -Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var Yp,nv=x(()=>{"use strict";Yp="mcp__(?!.*context-mode)"});var sv={};_e(sv,{QwenCodeAdapter:()=>Qp});import{readFileSync as nN,writeFileSync as rN,existsSync as oN}from"node:fs";import{resolve as rv,join as sN}from"node:path";import{homedir as ov}from"node:os";var Qp,iv=x(()=>{"use strict";ap();nv();Rn();Qp=class extends ds{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 rv(ov(),".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",Yp].join("|"),hooks:[{type:"command",command:qe(`${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:qe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/qwen-code/stop.mjs`)}]}]}}readSettings(){try{let e=nN(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){rN(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit","Stop"]){let i=Array.isArray(o[s])&&o[s].length>0;n.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 n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.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 n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let p=l.hooks??[];return p.some(m=>m.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(m.command))?p.every(m=>{if(!m.command)return!0;let h=m.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=m.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?oN(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[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",Yp].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:""},{name:"Stop",script:"qwen-code/stop.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:qe(`${e}/hooks/${a}`)}]},l=r[i];if(l&&Array.isArray(l)){let d=l.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:rv(sN(ov(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var av={};_e(av,{OMPAdapter:()=>nm});import{readFileSync as em,writeFileSync as iN,mkdirSync as aN}from"node:fs";import{resolve as tm,dirname as cN}from"node:path";import{homedir as uN}from"node:os";var nm,cv=x(()=>{"use strict";it();nm=class extends ve{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??tm(uN(),".omp","agent")}getSettingsPath(){return tm(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=em(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();aN(cN(n),{recursive:!0}),iN(n,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=em(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=tm(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(em(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode +Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var om,pS=x(()=>{"use strict";om="mcp__(?!.*context-mode)"});var hS={};ye(hS,{QwenCodeAdapter:()=>sm});import{readFileSync as bN,writeFileSync as xN,existsSync as vN}from"node:fs";import{resolve as mS,join as SN}from"node:path";import{homedir as fS}from"node:os";var sm,gS=x(()=>{"use strict";mp();pS();Pn();sm=class extends ms{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 mS(fS(),".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",om].join("|"),hooks:[{type:"command",command:qe(`${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:qe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/qwen-code/stop.mjs`)}]}]}}readSettings(){try{let e=bN(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){xN(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit","Stop"]){let i=Array.isArray(o[s])&&o[s].length>0;n.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 n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.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 n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let p=l.hooks??[];return p.some(m=>m.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(m.command))?p.every(m=>{if(!m.command)return!0;let h=m.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=m.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?vN(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[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",om].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:""},{name:"Stop",script:"qwen-code/stop.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:qe(`${e}/hooks/${a}`)}]},l=r[i];if(l&&Array.isArray(l)){let d=l.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:mS(SN(fS(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var yS={};ye(yS,{OMPAdapter:()=>cm});import{readFileSync as im,writeFileSync as kN,mkdirSync as wN}from"node:fs";import{resolve as am,dirname as EN}from"node:path";import{homedir as TN}from"node:os";var cm,_S=x(()=>{"use strict";st();cm=class extends _e{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??am(TN(),".omp","agent")}getSettingsPath(){return am(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=im(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();wN(EN(n),{recursive:!0}),kN(n,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=im(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=am(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(im(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode -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 uv={};_e(uv,{PiAdapter:()=>im});import{readFileSync as rm,writeFileSync as lN,mkdirSync as dN}from"node:fs";import{resolve as om,dirname as pN}from"node:path";import{homedir as sm}from"node:os";var im,lv=x(()=>{"use strict";it();im=class extends ve{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 om(sm(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=rm(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();dN(pN(n),{recursive:!0}),lN(n,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=om(sm(),".pi","extensions","context-mode","package.json");try{return JSON.parse(rm(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=om(sm(),".pi","extensions","context-mode","package.json");return JSON.parse(rm(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode +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 bS={};ye(bS,{PiAdapter:()=>pm});import{readFileSync as um,writeFileSync as $N,mkdirSync as PN}from"node:fs";import{resolve as lm,dirname as RN}from"node:path";import{homedir as dm}from"node:os";var pm,xS=x(()=>{"use strict";st();pm=class extends _e{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 lm(dm(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=um(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();PN(RN(n),{recursive:!0}),$N(n,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=lm(dm(),".pi","extensions","context-mode","package.json");try{return JSON.parse(um(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=lm(dm(),".pi","extensions","context-mode","package.json");return JSON.parse(um(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode -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 dv}from"node:os";import{resolve as am,join as bK}from"node:path";function pv(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?am(dv(),t.replace(/^~[/\\]?/,"")):am(t):am(dv(),".kimi-code")}var mv=x(()=>{"use strict"});var _v={};_e(_v,{KimiAdapter:()=>um,probeKimiCliVersion:()=>yv});import{execFileSync as mN}from"node:child_process";import{readFileSync as Hi,writeFileSync as fN,accessSync as hN,copyFileSync as gN,constants as yN,mkdirSync as fv}from"node:fs";import{resolve as _N,dirname as hv,join as ao}from"node:path";import{fileURLToPath as bN}from"node:url";function yv(t=mN){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function gv(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)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?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function vN(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(` -`)}function cm(t){return t.command.includes("context-mode hook kimi")}function kN(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var xN,Er,SN,um,bv=x(()=>{"use strict";it();Jt();mv();xN="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Er={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"},SN={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"]};um=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 pv()}getSettingsPath(){return ao(this.getConfigDir(),"config.toml")}getMcpPath(){return ao(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=ht(),n=e?ao(e,"context-mode","sessions"):ao(this.getConfigDir(),"context-mode","sessions");return fv(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=ht(),r=n?ao(n,"context-mode","memory"):ao(this.getConfigDir(),"memory");return e?ao(r,rt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:xN,hooks:[{type:"command",command:Er.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Er.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Er.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:Er.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Er.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Er.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Er.Stop}]}]}}readSettings(){try{return{_raw_toml:Hi(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=yv();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=Hi(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=gv(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(p=>p.event===a&&this.isExpectedHookEntry(a,p,u)),d=a==="PreCompact"?"warn":"fail";n.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&&cm(u)).length;c>1&&n.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 n}checkPluginRegistration(){try{let e=Hi(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&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 n=[],r=this.generateHookConfig(""),o="";try{o=Hi(this.getSettingsPath(),"utf-8")}catch{o=""}let s=gv(o),i=s.filter(l=>!cm(l)),a=[];for(let[l,d]of Object.entries(r)){let p=kN(l,d[0]);p&&a.push(p)}let c=s.some(cm),u=this.rebuildToml(o,i,a);return u!==o&&(fv(hv(this.getSettingsPath()),{recursive:!0}),fN(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{hN(n,yN.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=_N(hv(bN(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return Hi(e,"utf-8")}catch{return`# context-mode +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 vS}from"node:os";import{resolve as mm,join as ZK}from"node:path";function SS(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?mm(vS(),t.replace(/^~[/\\]?/,"")):mm(t):mm(vS(),".kimi-code")}var kS=x(()=>{"use strict"});var PS={};ye(PS,{KimiAdapter:()=>hm,probeKimiCliVersion:()=>$S});import{execFileSync as CN}from"node:child_process";import{readFileSync as Fi,writeFileSync as ON,accessSync as IN,copyFileSync as AN,constants as NN,mkdirSync as wS}from"node:fs";import{resolve as MN,dirname as ES,join as ao}from"node:path";import{fileURLToPath as DN}from"node:url";function $S(t=CN){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function TS(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)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?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function zN(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(` +`)}function fm(t){return t.command.includes("context-mode hook kimi")}function HN(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var jN,Er,LN,hm,RS=x(()=>{"use strict";st();Ut();kS();jN="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Er={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"},LN={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"]};hm=class extends _e{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 SS()}getSettingsPath(){return ao(this.getConfigDir(),"config.toml")}getMcpPath(){return ao(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=et(),n=e?ao(e,"context-mode","sessions"):ao(this.getConfigDir(),"context-mode","sessions");return wS(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=et(),r=n?ao(n,"context-mode","memory"):ao(this.getConfigDir(),"memory");return e?ao(r,Ge(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:jN,hooks:[{type:"command",command:Er.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Er.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Er.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:Er.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Er.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Er.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Er.Stop}]}]}}readSettings(){try{return{_raw_toml:Fi(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=$S();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=Fi(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=TS(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(p=>p.event===a&&this.isExpectedHookEntry(a,p,u)),d=a==="PreCompact"?"warn":"fail";n.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&&fm(u)).length;c>1&&n.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 n}checkPluginRegistration(){try{let e=Fi(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&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 n=[],r=this.generateHookConfig(""),o="";try{o=Fi(this.getSettingsPath(),"utf-8")}catch{o=""}let s=TS(o),i=s.filter(l=>!fm(l)),a=[];for(let[l,d]of Object.entries(r)){let p=HN(l,d[0]);p&&a.push(p)}let c=s.some(fm),u=this.rebuildToml(o,i,a);return u!==o&&(wS(ES(this.getSettingsPath()),{recursive:!0}),ON(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{IN(n,NN.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=MN(ES(DN(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return Fi(e,"utf-8")}catch{return`# context-mode -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,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return gN(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=(Er[e]??"").replace(/\\/g,"/"),s=SN[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){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=[...n,...r];if(a.length>0)for(let c of a)s.push(vN(c)),s.push("");return s.join(` -`)}}});var dm={};_e(dm,{PLATFORM_ENV_VARS:()=>bs,__resetClaudeCodePluginCacheForTests:()=>TN,__seedClaudeCodePluginCacheMissForTests:()=>$N,detectPlatform:()=>Qe,foreignIdentificationEnv:()=>ON,foreignWorkspaceEnv:()=>CN,getAdapter:()=>Fi,getEnvVarNames:()=>RN,getSessionDirSegments:()=>Ui,workspaceEnvVarsFor:()=>lm});import{existsSync as Ye,readFileSync as wN}from"node:fs";import{resolve as He}from"node:path";import{homedir as xv}from"node:os";function EN(){if(co!==null)return co!=="miss"&&co.hasCM;try{let t=He(xv(),".claude","plugins","installed_plugins.json"),e=wN(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return co={hasCM:o},o}catch{return co="miss",!1}}function TN(){co=null}function $N(){co="miss"}function RN(t){return(bs.get(t)??[]).map(e=>e.name)}function lm(t){return(bs.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function CN(t){let e=new Set;for(let[n,r]of bs)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function ON(t){let e=new Set;for(let[n,r]of bs)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function Ui(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];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 Qe(t){if(t?.name){let s=sx[t.name];if(s)return{platform:s,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","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of bs)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&EN()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=xv(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?He(n,s.replace(/^~[/\\]?/,"")):He(s):He(n,".copilot")})(),o=Ye(He(r,"mcp-config.json"))||Ye(He(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Ye(He(n,".local","bin","agy"))||Ye(He(n,".gemini","antigravity-cli"))||Ye(He(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:Ye(He(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ye(He(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ye(He(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ye(He(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ye(He(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ye(He(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ye(He(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ye(He(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Ye(He(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ye(He(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ye(He(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ye(He(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ye(He(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ye(He(n,".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 Fi(t){let e=t??Qe().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(hp(),fp));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(Hx(),zx));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(Zx(),Bx));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(Wx(),Vx));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>($p(),oS));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(lS(),uS));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(fS(),mS));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(kS(),vS));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(IS(),OS));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(Up(),NS));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(ZS(),BS));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(XS(),JS));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(tv(),ev));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(iv(),sv));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(cv(),av));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(lv(),uv));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(bv(),_v));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(hp(),fp));return new n}}}var co,PN,bs,uo=x(()=>{"use strict";ix();co=null;PN=[["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"},{name:"PI_CODING_AGENT",role:"identification"}]]],bs=new Map(PN)});import{resolve as Bi}from"node:path";import{homedir as pm}from"node:os";function Be(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Bi(pm(),e.replace(/^~[/\\]?/,"")):Bi(e):Bi(pm(),".claude")}function IN(t=process.env){return Bi(Be(t),"settings.json")}function mm(t=process.env){let e=[],n=Qe();if(n.platform!=="claude-code"){let o=Ui(n.platform);o&&o.length>0&&e.push(Bi(pm(),...o,"settings.json"))}let r=IN(t);return e.includes(r)||e.push(r),e}var Sr=x(()=>{"use strict";uo()});import{readdirSync as AN,statSync as NN,lstatSync as MN,realpathSync as Sv,existsSync as DN,readFileSync as jN}from"node:fs";import{join as kv,extname as LN,relative as wv,sep as zN,resolve as HN}from"node:path";function qN(t){let e="";for(let n=0;nr.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function WN(t,e){return wv(t,e).split(zN).join("/")}function Ev(t,e={}){let{include:n,exclude:r,maxDepth:o=BN,maxFiles:s=ZN,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Sv(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:FN).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...UN,...r??[],...a?VN(u):[]],p=n??[],f=[],m=new Set([u]),h=0,g=!1;function y(_,b){if(g||b>o)return;let S;try{S=AN(_,{withFileTypes:!0})}catch{return}for(let T of S){if(g)return;let M=kv(_,T.name),v=WN(u,M);if(vv(v,d))continue;let $=T.isDirectory(),P=T.isFile(),A=!1;try{A=MN(M).isSymbolicLink()}catch{continue}if(A){if(!c)continue;let C;try{C=Sv(M)}catch{continue}let H=wv(u,C);if((H.startsWith("..")||HN(H)===C)&&H.startsWith("..")||m.has(C))continue;m.add(C);try{let W=NN(C);$=W.isDirectory(),P=W.isFile()}catch{continue}}if($){y(M,b+1);continue}if(!P)continue;let R=LN(M).toLowerCase();if(l.includes(R)&&!(p.length>0&&!vv(v,p))){if(h++,f.length>=s){g=!0;return}f.push(M)}}}return y(u,0),{files:f,capped:g,totalSeen:h}}var UN,FN,BN,ZN,Tv=x(()=>{"use strict";UN=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],FN=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],BN=5,ZN=200});import{readFileSync as $v,readdirSync as Av,unlinkSync as hm,existsSync as fm,statSync as Gc,openSync as Pv,fstatSync as Rv,closeSync as Cv}from"node:fs";import{createHash as Ov}from"node:crypto";import{tmpdir as Nv}from"node:os";import{join as gm}from"node:path";function Mv(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function KN(t,e="AND"){let n=Mv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!xs.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function GN(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=Mv(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!xs.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function JN(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function XN(t){return t<=4?1:t<=12?2:3}function ym(){let t=Nv(),e=0;try{let n=Av(t);for(let r of n){let o=r.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=gm(t,r);for(let a of["","-wal","-shm"])try{hm(i+a)}catch{}e++}}}catch{}return e}function _m(t,e){let n=0;try{if(!fm(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=Av(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=gm(t,s),c=Gc(i).mtimeMs0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{hm(i+u)}catch{}n++}}catch{}}catch{}return n}function nM(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function rM(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=0,o=Math.min(t.length,e.length)-1;for(let s=0;ss&&(s=u)}let a=s-o;if(a=e[i].length)break}return r}var xs,Kc,YN,QN,eM,Iv,tM,Ss,bm=x(()=>{"use strict";hr();Tv();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"]);Kc=4096,YN=3,QN=200,eM=5e3,Iv=80,tM=.5;Ss=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#f;#h;#g;#y;#_;#b;#x;#S;#v;#k;#w;#E;#T;#$;#P;#R;#C;#O;#I;#A;#N;#M;#D;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=nt();this.#t=e??gm(Nv(),`context-mode-${process.pid}.db`),rs(this.#t);let r;try{r=new n(this.#t,{timeout:3e4}),ns(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(kc(s)){vc(this.#t),rs(this.#t);try{r=new n(this.#t,{timeout:3e4}),ns(r)}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=r,this.#B(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{hm(this.#t+e)}catch{}}#B(){this.#e.exec(` +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,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return AN(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=(Er[e]??"").replace(/\\/g,"/"),s=LN[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){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=[...n,...r];if(a.length>0)for(let c of a)s.push(zN(c)),s.push("");return s.join(` +`)}}});import{homedir as CS}from"node:os";import{resolve as gm}from"node:path";function ym(){let t=process.env.VIBE_HOME;return t?t.startsWith("~")?gm(CS(),t.replace(/^~[/\\]?/,"")):gm(t):gm(CS(),".vibe")}var OS=x(()=>{"use strict"});var Bi,Xc,co,IS=x(()=>{"use strict";Bi={PRE_TOOL:"pre_tool",POST_TOOL:"post_tool",POST_AGENT:"post_agent"},Xc="bash",co={pre_tool:"context-mode hook mistral-vibe pretooluse",post_tool:"context-mode hook mistral-vibe posttooluse",post_agent:"context-mode hook mistral-vibe postagent"}});var DS={};ye(DS,{MistralVibeAdapter:()=>bm,probeVibeCliVersion:()=>_m,resolveVibeConfigDir:()=>ym});import{execFileSync as UN}from"node:child_process";import{readFileSync as Yc,writeFileSync as FN,mkdirSync as AS}from"node:fs";import{dirname as BN,join as uo}from"node:path";function NS(t){let e=[],n=t.split(/\r?\n/),r=null,o=()=>{r&&r.name&&r.type&&r.command&&e.push(r),r=null};for(let s of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(s)){o(),r={};continue}if(!r)continue;let i=s.match(/^\s*(\w+)\s*=\s*"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$/);if(i){let u=i[1],l=i[2].replace(/\\"/g,'"').replace(/\\\\/g,"\\");r[u]=l;continue}let a=s.match(/^\s*(\w+)\s*=\s*(-?\d+(?:\.\d+)?)\s*(?:#.*)?$/);if(a){r[a[1]]=Number(a[2]);continue}let c=s.match(/^\s*(\w+)\s*=\s*(true|false)\s*(?:#.*)?$/);if(c){r[c[1]]=c[2]==="true";continue}}return o(),e}function ZN(t){let e=r=>r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=["[[hooks]]"];return n.push(`name = "${e(t.name)}"`),n.push(`type = "${e(t.type)}"`),t.match!==void 0&&n.push(`match = "${e(t.match)}"`),n.push(`command = "${e(t.command)}"`),t.timeout!==void 0&&n.push(`timeout = ${t.timeout}`),t.strict!==void 0&&n.push(`strict = ${t.strict}`),t.description!==void 0&&n.push(`description = "${e(t.description)}"`),n.join(` +`)}function MS(t){return t.command.includes("context-mode hook mistral-vibe")}function _m(t=UN){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","vibe --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("vibe",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (empty version output)"}catch{return null}}var bm,jS=x(()=>{"use strict";st();Ut();OS();IS();bm=class extends _e{constructor(){super([".vibe"])}name="Mistral Vibe";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:n.session_id??this.fallbackSessionId(),projectDir:n.cwd??void 0,raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output_text??void 0,isError:n.tool_status==="failure"||!!n.tool_error,sessionId:n.session_id??this.fallbackSessionId(),projectDir:n.cwd??void 0,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){let n={hook_specific_output:{tool_input:e.updatedInput}};return e.reason&&(n.system_message=`context-mode: ${e.reason}`),n}return{}}formatPostToolUseResponse(e){return e.additionalContext?{hook_specific_output:{additional_context:e.additionalContext}}:{}}getConfigDir(e){return ym()}getSettingsPath(){return uo(this.getConfigDir(),"config.toml")}getHooksPath(){return uo(this.getConfigDir(),"hooks.toml")}getSessionDir(){let e=et(),n=e?uo(e,"context-mode","sessions"):uo(this.getConfigDir(),"context-mode","sessions");return AS(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=et(),r=n?uo(n,"context-mode","memory"):uo(this.getConfigDir(),"memory");return e?uo(r,Ge(e)):r}generateHookConfig(e){return{pre_tool:[{matcher:Xc,hooks:[{type:"command",command:co.pre_tool}]}],post_tool:[{matcher:"",hooks:[{type:"command",command:co.post_tool}]}]}}readSettings(){try{return{_raw_toml:Yc(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}writeHooksFile(e){let n=[];try{let i=Yc(this.getHooksPath(),"utf-8");n=NS(i)}catch{}let o=[...n.filter(i=>!MS(i)),...e],s=o.map(ZN).join(` + +`)+(o.length>0?` +`:"");AS(BN(this.getHooksPath()),{recursive:!0}),FN(this.getHooksPath(),s,{encoding:"utf-8",mode:384})}validateHooks(e){let n=[],r=_m();n.push({check:"Mistral Vibe CLI binary",status:r?"pass":"warn",message:r?`vibe --version resolved to ${r}`:"Could not run vibe --version; hooks need the Mistral Vibe CLI available on PATH",...r?{}:{fix:"Install Mistral Vibe (uv tool install mistral-vibe) and ensure vibe is on PATH"}});let o="";try{o=Yc(this.getHooksPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Run context-mode upgrade to generate the initial hooks.toml"}),n}let i=NS(o).filter(MS),a=[{event:Bi.PRE_TOOL,command:co.pre_tool,matcher:Xc},{event:Bi.POST_TOOL,command:co.post_tool}];for(let c of a){let u=i.find(l=>l.type===c.event);if(!u){n.push({check:`${c.event} hook`,status:"fail",message:`Missing context-mode ${c.event} hook in ${this.getHooksPath()}`,fix:"Run context-mode upgrade to install missing hooks"});continue}if(c.matcher&&u.match!==c.matcher){n.push({check:`${c.event} hook`,status:"warn",message:`Matcher drift: expected "${c.matcher}", got "${u.match??""}"`,fix:"Run context-mode upgrade to re-sync hook matchers"});continue}n.push({check:`${c.event} hook`,status:"pass",message:`Hook installed with command "${u.command}"`})}return n}checkPluginRegistration(){try{let e=Yc(this.getSettingsPath(),"utf-8"),n=e.includes("context-mode"),r=/^\s*\[\[mcp_servers\]\]/m.test(e);return r&&n?{check:"MCP registration",status:"pass",message:`context-mode found in ${this.getSettingsPath()} [[mcp_servers]]`}:r?{check:"MCP registration",status:"fail",message:"No context-mode entry in [[mcp_servers]]",fix:`Add a [[mcp_servers]] block for context-mode to ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [[mcp_servers]] section in config.toml",fix:`Add [[mcp_servers]] name = "context-mode" ... to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return _m()??"not installed"}configureAllHooks(e){let n=[],r=[{name:"context-mode-pretool",type:Bi.PRE_TOOL,match:Xc,command:co.pre_tool,timeout:30,strict:!1,description:"Route bash commands through context-mode sandbox"},{name:"context-mode-posttool",type:Bi.POST_TOOL,command:co.post_tool,timeout:30,strict:!1,description:"Capture session events for context-mode"}];return this.writeHooksFile(r),n.push(`Wrote ${r.length} hooks to ${this.getHooksPath()}`),n.push(`Note: add context-mode to [[mcp_servers]] in ${this.getSettingsPath()} manually \u2014 see configs/mistral-vibe/AGENTS.md`),n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}fallbackSessionId(){return`vibe-ppid-${process.ppid}`}}});var vm={};ye(vm,{PLATFORM_ENV_VARS:()=>vs,__resetClaudeCodePluginCacheForTests:()=>WN,__seedClaudeCodePluginCacheMissForTests:()=>KN,detectPlatform:()=>tt,foreignIdentificationEnv:()=>YN,foreignWorkspaceEnv:()=>XN,getAdapter:()=>qi,getEnvVarNames:()=>JN,getSessionDirSegments:()=>Zi,workspaceEnvVarsFor:()=>xm});import{existsSync as Je,readFileSync as qN}from"node:fs";import{resolve as Ne}from"node:path";import{homedir as LS}from"node:os";function VN(){if(lo!==null)return lo!=="miss"&&lo.hasCM;try{let t=Ne(LS(),".claude","plugins","installed_plugins.json"),e=qN(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return lo={hasCM:o},o}catch{return lo="miss",!1}}function WN(){lo=null}function KN(){lo="miss"}function JN(t){return(vs.get(t)??[]).map(e=>e.name)}function xm(t){return(vs.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function XN(t){let e=new Set;for(let[n,r]of vs)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function YN(t){let e=new Set;for(let[n,r]of vs)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function Zi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"mistral-vibe":return[".vibe"];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 tt(t){if(t?.name){let i=hx[t.name];if(i)return{platform:i,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","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi","mistral-vibe"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[i,a]of vs)if(a.some(c=>c.detect!==!1&&process.env[c.name]))return i==="vscode-copilot"&&VN()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:i,confidence:"high",reason:`${a.filter(c=>c.detect!==!1).map(c=>c.name).join(" or ")} env var set`};let n=LS(),r=(()=>{let i=process.env.COPILOT_HOME;return i&&i.trim()!==""?i.startsWith("~")?Ne(n,i.replace(/^~[/\\]?/,"")):Ne(i):Ne(n,".copilot")})(),o=Je(Ne(r,"mcp-config.json"))||Je(Ne(r,"hooks","context-mode.json"));if(process.env.COPILOT_HOME?.trim()&&o)return{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"};if(Je(Ne(n,".local","bin","agy"))||Je(Ne(n,".gemini","antigravity-cli"))||Je(Ne(n,".gemini","config","mcp_config.json")))return{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"};if(o)return{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"};if(Je(Ne(n,".claude")))return{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"};if(Je(Ne(n,".gemini")))return{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"};if(Je(Ne(n,".codex")))return{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"};if(Je(Ne(n,".kiro")))return{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"};if(Je(Ne(n,".omp")))return{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"};if(Je(Ne(n,".pi")))return{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"};if(Je(Ne(n,".qwen")))return{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"};if(Je(Ne(n,".kimi-code")))return{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"};let s=process.env.VIBE_HOME??Ne(n,".vibe");return Je(s)?{platform:"mistral-vibe",confidence:"medium",reason:process.env.VIBE_HOME?`$VIBE_HOME=${s} directory exists`:"~/.vibe/ directory exists"}:Je(Ne(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Je(Ne(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Je(Ne(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Je(Ne(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Je(Ne(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Je(Ne(n,".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 qi(t){let e=t??tt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(vp(),xp));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(Jx(),Gx));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(ev(),Qx));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(rv(),nv));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Ap(),fv));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(xv(),bv));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(wv(),kv));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(Av(),Iv));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(Fv(),Uv));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(Wp(),Zv));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(eS(),Qv));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(aS(),iS));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(dS(),lS));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(gS(),hS));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(_S(),yS));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(xS(),bS));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(RS(),PS));return new n}case"mistral-vibe":{let{MistralVibeAdapter:n}=await Promise.resolve().then(()=>(jS(),DS));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(vp(),xp));return new n}}}var lo,GN,vs,po=x(()=>{"use strict";gx();lo=null;GN=[["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"},{name:"PI_CODING_AGENT",role:"identification"}]],["mistral-vibe",[{name:"VIBE_HOME",role:"workspace",detect:!1}]]],vs=new Map(GN)});import{resolve as Vi}from"node:path";import{homedir as Sm}from"node:os";function Be(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Vi(Sm(),e.replace(/^~[/\\]?/,"")):Vi(e):Vi(Sm(),".claude")}function QN(t=process.env){return Vi(Be(t),"settings.json")}function km(t=process.env){let e=[],n=tt();if(n.platform!=="claude-code"){let o=Zi(n.platform);o&&o.length>0&&e.push(Vi(Sm(),...o,"settings.json"))}let r=QN(t);return e.includes(r)||e.push(r),e}var vr=x(()=>{"use strict";po()});import{readdirSync as eM,statSync as tM,lstatSync as nM,realpathSync as zS,existsSync as rM,readFileSync as oM}from"node:fs";import{join as US,extname as sM,relative as FS,sep as iM,resolve as aM}from"node:path";function pM(t){let e="";for(let n=0;nr.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function fM(t,e){return FS(t,e).split(iM).join("/")}function BS(t,e={}){let{include:n,exclude:r,maxDepth:o=lM,maxFiles:s=dM,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=zS(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:uM).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...cM,...r??[],...a?mM(u):[]],p=n??[],f=[],m=new Set([u]),h=0,g=!1;function y(_,b){if(g||b>o)return;let v;try{v=eM(_,{withFileTypes:!0})}catch{return}for(let T of v){if(g)return;let M=US(_,T.name),S=fM(u,M);if(HS(S,d))continue;let $=T.isDirectory(),P=T.isFile(),A=!1;try{A=nM(M).isSymbolicLink()}catch{continue}if(A){if(!c)continue;let C;try{C=zS(M)}catch{continue}let H=FS(u,C);if((H.startsWith("..")||aM(H)===C)&&H.startsWith("..")||m.has(C))continue;m.add(C);try{let W=tM(C);$=W.isDirectory(),P=W.isFile()}catch{continue}}if($){y(M,b+1);continue}if(!P)continue;let R=sM(M).toLowerCase();if(l.includes(R)&&!(p.length>0&&!HS(S,p))){if(h++,f.length>=s){g=!0;return}f.push(M)}}}return y(u,0),{files:f,capped:g,totalSeen:h}}var cM,uM,lM,dM,ZS=x(()=>{"use strict";cM=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],uM=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],lM=5,dM=200});import{readFileSync as qS,readdirSync as XS,unlinkSync as Em,existsSync as wm,statSync as eu,openSync as VS,fstatSync as WS,closeSync as KS}from"node:fs";import{createHash as GS}from"node:crypto";import{tmpdir as YS}from"node:os";import{join as Tm}from"node:path";function QS(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function hM(t,e="AND"){let n=QS(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!Ss.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function gM(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=QS(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!Ss.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function yM(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function _M(t){return t<=4?1:t<=12?2:3}function $m(){let t=YS(),e=0;try{let n=XS(t);for(let r of n){let o=r.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=Tm(t,r);for(let a of["","-wal","-shm"])try{Em(i+a)}catch{}e++}}}catch{}return e}function Pm(t,e){let n=0;try{if(!wm(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=XS(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Tm(t,s),c=eu(i).mtimeMs0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Em(i+u)}catch{}n++}}catch{}}catch{}return n}function kM(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function wM(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=0,o=Math.min(t.length,e.length)-1;for(let s=0;ss&&(s=u)}let a=s-o;if(a=e[i].length)break}return r}var Ss,Qc,bM,xM,vM,JS,SM,ks,Rm=x(()=>{"use strict";hr();ZS();Ss=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"]);Qc=4096,bM=3,xM=200,vM=5e3,JS=80,SM=.5;ks=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#f;#h;#g;#y;#_;#b;#x;#v;#S;#k;#w;#E;#T;#$;#P;#R;#C;#O;#I;#A;#N;#M;#D;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=ot();this.#t=e??Tm(YS(),`context-mode-${process.pid}.db`),ss(this.#t);let r;try{r=new n(this.#t,{timeout:3e4}),os(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Tc(s)){Ec(this.#t),ss(this.#t);try{r=new n(this.#t,{timeout:3e4}),os(r)}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=r,this.#B(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Em(this.#t+e)}catch{}}#B(){this.#e.exec(` CREATE TABLE IF NOT EXISTS sources ( id INTEGER PRIMARY KEY AUTOINCREMENT, label TEXT NOT NULL, @@ -338,7 +342,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde WHERE chunks_trigram MATCH ? AND sources.label = ? ORDER BY rank LIMIT ? - `),this.#v=this.#e.prepare(` + `),this.#S=this.#e.prepare(` SELECT chunks.title, chunks.content, @@ -428,7 +432,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ? ORDER BY rank LIMIT ? - `),this.#S=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#P=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#R=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label + `),this.#v=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#P=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#R=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label FROM chunks c JOIN sources s ON s.id = c.source_id WHERE c.source_id = ? @@ -437,7 +441,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde (SELECT COUNT(*) FROM sources) AS sources, (SELECT COUNT(*) FROM chunks) AS chunks, (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks - `),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=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:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let p=Pv(r,"r");try{if(!Rv(p).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=$v(p,"utf-8")}finally{Cv(p)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?Ov("sha256").update(a).digest("hex"):void 0;return fr(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=Ev(n,i),c=0,u=0,l=0,d=0;for(let p of a.files){if(s&&s(p)){l++;continue}try{let f=r?`${r}:${p}`:p,m=this.index({path:p,source:f,attribution:o});c++,u+=m.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:r??n}}indexPlainText(e,n,r=20,o,s=Kc){if(!e||e.trim().length===0)return this.#d([],n,"",void 0,void 0,o);let i=this.#J(e,r,s);return fr(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}indexJSON(e,n,r=Kc,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];return this.#F(s,[],i,r),i.length===0?this.indexPlainText(e,n,void 0,o,r):fr(()=>this.#d(i,n,e,void 0,void 0,o))}#d(e,n,r,o,s,i){let a=e.filter(p=>p.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(n),this.#l.run(n),this.#f.run(n),e.length===0){let h=this.#o.run(n,o??null,s??null);return Number(h.lastInsertRowid)}let p=this.#s.run(n,e.length,a,o??null,s??null),f=Number(p.lastInsertRowid),m=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,m),this.#c.run(h.title,h.content,f,g,null,c,u,m)}return f})();return r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=KN(e,o),c,u;return r&&s?(c=i==="exact"?this.#w:this.#k,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#v,u=[a,s,n]):(c=this.#h,u=[a,n]),fr(()=>this.#L(c.all(...u)))}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=GN(e,o);if(!a)return[];let c,u;return r&&s?(c=i==="exact"?this.#$:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#x:this.#b,u=[a,this.#p(r,i),n]):s?(c=this.#E,u=[a,s,n]):(c=this.#_,u=[a,n]),fr(()=>this.#L(c.all(...u)))}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=XN(n.length),o=this.#S.all(n.length-r,n.length+r),s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=JN(n,u);l=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(n,c),c}#z(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"OR",o,s),l=new Map,d=p=>`${p.source}::${p.title}`;for(let[p,f]of c.entries()){let m=d(f),h=l.get(m);h?h.score+=1/(60+p+1):l.set(m,{result:f,score:1/(60+p+1)})}for(let[p,f]of u.entries()){let m=d(f),h=l.get(m);h?h.score+=1/(60+p+1):l.set(m,{result:f,score:1/(60+p+1)})}return Array.from(l.values()).sort((p,f)=>f.score-p.score).slice(0,n).map(({result:p,score:f})=>({...p,rank:-f}))}#H(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!xs.has(i)),s=o.length>0?o:r;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,p=0;if(s.length>=2){let f=i.content.toLowerCase(),m=s.map(h=>nM(f,h));if(!m.some(h=>h.length===0)){d=1/(1+oM(m)/Math.max(f.length,1));let g=rM(m,s);p=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#z(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#H(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(h=>h.length>=3&&!xs.has(h)),p=d.join(" "),m=d.map(h=>this.fuzzyCorrect(h)??h).join(" ");if(m!==p){let h=this.#z(m,a,r,o,s),g=c?h.filter(c):h;if(g.length>0)return this.#H(g.slice(0,n),m).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){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 n of e)try{if(!fm(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=Gc(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=Pv(n.file_path,"r"),i;try{if(!Rv(s).isFile())continue;i=$v(s,"utf-8")}finally{Cv(s)}if(Ov("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let n=this.#A.get(e);return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){return this.#P.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.#R.all(e).map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r=this.#C.get(e);if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#O.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!xs.has(p)));for(let p of d)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let p=Math.log(o/d),f=Math.min(l.length/20,.5),m=/[_]/.test(l),h=l.length>=12,g=m?1.5:h?.8:0;return{word:l,score:p+f+g}}).sort((l,d)=>d.score-l.score).slice(0,n).map(l=>l.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#N.run(o),this.#M.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return Gc(this.#t).size}catch{return 0}}#U(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#U(),os(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!xs.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=Kc){let r=[],o=e.split(` + `),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=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:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let p=VS(r,"r");try{if(!WS(p).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=qS(p,"utf-8")}finally{KS(p)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?GS("sha256").update(a).digest("hex"):void 0;return fr(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=BS(n,i),c=0,u=0,l=0,d=0;for(let p of a.files){if(s&&s(p)){l++;continue}try{let f=r?`${r}:${p}`:p,m=this.index({path:p,source:f,attribution:o});c++,u+=m.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:r??n}}indexPlainText(e,n,r=20,o,s=Qc){if(!e||e.trim().length===0)return this.#d([],n,"",void 0,void 0,o);let i=this.#J(e,r,s);return fr(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}indexJSON(e,n,r=Qc,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];return this.#F(s,[],i,r),i.length===0?this.indexPlainText(e,n,void 0,o,r):fr(()=>this.#d(i,n,e,void 0,void 0,o))}#d(e,n,r,o,s,i){let a=e.filter(p=>p.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(n),this.#l.run(n),this.#f.run(n),e.length===0){let h=this.#o.run(n,o??null,s??null);return Number(h.lastInsertRowid)}let p=this.#s.run(n,e.length,a,o??null,s??null),f=Number(p.lastInsertRowid),m=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,m),this.#c.run(h.title,h.content,f,g,null,c,u,m)}return f})();return r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=hM(e,o),c,u;return r&&s?(c=i==="exact"?this.#w:this.#k,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#S,u=[a,s,n]):(c=this.#h,u=[a,n]),fr(()=>this.#L(c.all(...u)))}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=gM(e,o);if(!a)return[];let c,u;return r&&s?(c=i==="exact"?this.#$:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#x:this.#b,u=[a,this.#p(r,i),n]):s?(c=this.#E,u=[a,s,n]):(c=this.#_,u=[a,n]),fr(()=>this.#L(c.all(...u)))}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=_M(n.length),o=this.#v.all(n.length-r,n.length+r),s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=yM(n,u);l=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(n,c),c}#z(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"OR",o,s),l=new Map,d=p=>`${p.source}::${p.title}`;for(let[p,f]of c.entries()){let m=d(f),h=l.get(m);h?h.score+=1/(60+p+1):l.set(m,{result:f,score:1/(60+p+1)})}for(let[p,f]of u.entries()){let m=d(f),h=l.get(m);h?h.score+=1/(60+p+1):l.set(m,{result:f,score:1/(60+p+1)})}return Array.from(l.values()).sort((p,f)=>f.score-p.score).slice(0,n).map(({result:p,score:f})=>({...p,rank:-f}))}#H(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!Ss.has(i)),s=o.length>0?o:r;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,p=0;if(s.length>=2){let f=i.content.toLowerCase(),m=s.map(h=>kM(f,h));if(!m.some(h=>h.length===0)){d=1/(1+EM(m)/Math.max(f.length,1));let g=wM(m,s);p=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#z(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#H(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(h=>h.length>=3&&!Ss.has(h)),p=d.join(" "),m=d.map(h=>this.fuzzyCorrect(h)??h).join(" ");if(m!==p){let h=this.#z(m,a,r,o,s),g=c?h.filter(c):h;if(g.length>0)return this.#H(g.slice(0,n),m).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){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 n of e)try{if(!wm(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=eu(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=VS(n.file_path,"r"),i;try{if(!WS(s).isFile())continue;i=qS(s,"utf-8")}finally{KS(s)}if(GS("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let n=this.#A.get(e);return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){return this.#P.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.#R.all(e).map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r=this.#C.get(e);if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#O.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!Ss.has(p)));for(let p of d)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let p=Math.log(o/d),f=Math.min(l.length/20,.5),m=/[_]/.test(l),h=l.length>=12,g=m?1.5:h?.8:0;return{word:l,score:p+f+g}}).sort((l,d)=>d.score-l.score).slice(0,n).map(l=>l.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#N.run(o),this.#M.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return eu(this.#t).size}catch{return 0}}#U(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#U(),is(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!Ss.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=Qc){let r=[],o=e.split(` `),s=[],i=[],a="",c=()=>{let l=i.join(` `).trim();if(l.length===0)return;let d=this.#ee(s,a),p=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=n){r.push({title:d,content:l,hasCode:p}),i=[];return}let f=l.split(/\n\n+/),m=[],h=1,g=()=>{if(m.length===0)return;let y=m.join(` @@ -445,62 +449,63 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde `);Buffer.byteLength(_)>n&&m.length>1&&(m.pop(),g(),m=[y])}g(),i=[]},u=0;for(;u0&&s[s.length-1].level>=f;)s.pop();s.push({level:f,text:m}),a=m,i.push(l),u++;continue}let p=l.match(/^(`{3,})(.*)?$/);if(p){let f=p[1],m=[l];for(u++;un)break;r+=s,o+=i}return r.length===0?[...e][0]??"":r}#m(e,n,r){let o=[],s=[],i=1,a=()=>{if(s.length===0)return;let c=s.join(` `),u=i===1?n:`${n} (${i})`;o.push({title:u,content:c}),i++,s=[]};for(let c of e){if(Buffer.byteLength(c)>r){a();let l=c,d=1;for(;l.length>0;){let p=this.#G(l,r);if(p.lengthp.length*tM&&(p=p.slice(0,g))}let f=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:f,content:p}),l=l.slice(p.length),d++,i++}continue}let u=s.length>0?s.join(` +`),g=Math.max(m,h);g>p.length*SM&&(p=p.slice(0,g))}let f=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:f,content:p}),l=l.slice(p.length),d++,i++}continue}let u=s.length>0?s.join(` `)+` -`+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=Kc){let o=e.split(/\n\s*\n/);if(o.length>=YN&&o.length<=QN&&o.every(u=>Buffer.byteLength(u){let d=u.trim();if(d.length===0)return[];let p=d.split(` -`)[0].slice(0,Iv)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:p,content:d}]:this.#m(d.split(` +`+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=Qc){let o=e.split(/\n\s*\n/);if(o.length>=bM&&o.length<=xM&&o.every(u=>Buffer.byteLength(u){let d=u.trim();if(d.length===0)return[];let p=d.split(` +`)[0].slice(0,JS)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:p,content:d}]:this.#m(d.split(` `),p,r)});let s=e.split(` -`);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#m(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u0?n.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))){r.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.#F(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;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])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;lo&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}}});import{readFileSync as jv,realpathSync as Sm}from"node:fs";import{relative as sM,resolve as lo,sep as iM}from"node:path";function Lv(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function aM(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function cM(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Dv(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function uM(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=cM(o),a=Dv(s);n=`^${i}(\\s${a})?$`}else n=`^${Dv(t)}$`;return new RegExp(n,e?"i":"")}function lM(t,e=!1){let n="",r=0;for(;r=0&&t[r]==="\\";r--)n++;return n%2===1}function pM(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===` -`||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function Hv(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),p=t.slice(d,c);e.push(p)}}}return e}function Uv(t){let e=[],n=pM(t);for(let r of n){e.push(r);for(let o of Hv(r))e.push(...Uv(o))}return e}function xm(t){let e;try{e=jv(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Lv(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function vm(t,e){let n=[];if(t){let o=lo(t,".claude","settings.local.json"),s=xm(o);s&&n.push(s);let i=lo(t,".claude","settings.json"),a=xm(i);a&&n.push(a)}let r=e!==void 0?[e]:mm();for(let o of r){let s=xm(o);s&&n.push(s)}return n}function po(t,e,n){return km(t,"deny",e,n)}function km(t,e,n,r){let o=[],s=a=>{let c;try{c=jv(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.[e];if(!Array.isArray(l))return[];let d=[];for(let p of l){if(typeof p!="string")continue;let f=aM(p);f&&f.tool===t&&d.push(f.glob)}return d};if(n){let a=s(lo(n,".claude","settings.local.json"));a!==null&&o.push(a);let c=s(lo(n,".claude","settings.json"));c!==null&&o.push(c)}let i=r!==void 0?[r]:mm();for(let a of i){let c=s(a);c!==null&&o.push(c)}return o}function wm(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=Uv(t);for(let o of r)for(let s of e){let i=dM(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Tr(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=lo(r,t);s.add(o(i));try{s.add(o(Sm(i)))}catch{}}for(let i of e)for(let a of i){let c=lM(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function mM(t,e,n=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let r=lo(e),o=lo(e,t),s=(i,a)=>{let c=i,u=a;if(n&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=sM(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+iM)||fM(l))};if(!s(r,o))return!1;try{let i=Sm(r),a=Sm(o);if(!s(i,a))return!1}catch{}return!0}function fM(t){if(t.startsWith("/"))return!0;if(t.length>=3&&t[1]===":"&&(t[2]==="\\"||t[2]==="/")){let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122}return!1}function Fv(t,e,n=[],r=process.platform==="win32"||process.platform==="darwin"){return mM(t,e,r)?{allowed:!0,reason:"inside"}:n.some(o=>o.length>0)&&Tr(t,n,r,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}function gM(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function Bv(t,e){let n=hM[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...gM(t)),r}var hM,Em=x(()=>{"use strict";Sr();hM={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 Vv={};_e(Vv,{healClaudeJsonMcpArgs:()=>OM,healInstalledPlugins:()=>PM,healMcpJsonArgs:()=>CM,healPluginJsonMcpServers:()=>Jc,healSettingsEnabledPlugins:()=>RM,sweepStaleMcpJson:()=>Xc});import{existsSync as Xn,readFileSync as vs,writeFileSync as qi,readdirSync as EM,unlinkSync as TM,statSync as $M}from"node:fs";import{resolve as vt,sep as mo}from"node:path";function PM({registryPath:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!Xn(t))return{healed:[],skipped:"no-registry"};let r;try{r=vs(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(r)}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[n]||[];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=vt(u),d=vt(e)+mo;if(!l.startsWith(d))continue;let p=vt(u,".claude-plugin","plugin.json");if(!Xn(p))continue;let f=null;try{let m=JSON.parse(vs(p,"utf-8"));m&&typeof m.version=="string"&&m.version&&(f=m.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[n];(c==null||c===!1||c==="")&&(o.enabledPlugins[n]=!0,i.push("enabled-plugins"))}if(i.length>0)try{qi(t,JSON.stringify(o,null,2)+` -`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function RM({settingsPath:t,pluginKey:e}){if(!t||!Xn(t))return{healed:[],skipped:"no-settings"};let n;try{n=vs(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let r;try{r=JSON.parse(n)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!r.enabledPlugins||typeof r.enabledPlugins!="object"||Array.isArray(r.enabledPlugins))&&(r.enabledPlugins={});let s=r.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(r.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{qi(t,JSON.stringify(r,null,2)+` -`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function Jc({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=vt(t),o=vt(e)+mo;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=vt(t,".claude-plugin","plugin.json");if(!Xn(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=vs(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=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,f=p.map(h=>typeof h!="string"||h===Zi?h:/[/\\]start\.mjs$/.test(h)?Zi:h);if(f.some((h,g)=>h!==p[g])){l.args=f,d.push("plugin-json-args");try{qi(s,JSON.stringify(a,null,2)+` -`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function CM({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=vt(t),o=vt(e)+mo;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=vt(t,".mcp.json");if(!Xn(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=vs(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=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,f=p.map(h=>typeof h!="string"||h===Zi?h:h==="./start.mjs"||h==="start.mjs"||/[/\\]start\.mjs$/.test(h)?Zi:h);if(f.some((h,g)=>h!==p[g])){l.args=f,d.push("mcp-json-args");try{qi(s,JSON.stringify(a,null,2)+` -`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function OM({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:n}){if(!t||!Xn(t))return{healed:[],skipped:"no-claude-json"};let r;try{r=vs(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(r)}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=vt(n),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{"use strict";Zi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,$m,z,An,Vi=x(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,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 r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})($m||($m={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),An=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 I,NM,Ct,Yc=x(()=>{Vi();I=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"]),NM=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=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;cn.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Ct.create=t=>new Ct(t)});var MM,Yn,Pm=x(()=>{Yc();Vi();MM=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===z.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ce.assertNever(t)}return{message:n}},Yn=MM});function DM(t){Kv=t}function ks(){return Kv}var Kv,Qc=x(()=>{Pm();Kv=Yn});function D(t,e){let n=ks(),r=Wi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Yn?void 0:Yn].filter(o=>!!o)});t.common.issues.push(r)}var Wi,jM,at,G,fo,gt,eu,tu,$r,ws,Rm=x(()=>{Qc();Pm();Wi=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},jM=[];at=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return G;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return G;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},G=Object.freeze({status:"aborted"}),fo=t=>({status:"dirty",value:t}),gt=t=>({status:"valid",value:t}),eu=t=>t.status==="aborted",tu=t=>t.status==="dirty",$r=t=>t.status==="valid",ws=t=>typeof Promise<"u"&&t instanceof Promise});var Gv=x(()=>{});var B,Jv=x(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function ek(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function eD(t){return new RegExp(`^${ek(t)}$`)}function tk(t){let e=`${Qv}T${ek(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function tD(t,e){return!!((e==="v4"||!e)&&WM.test(t)||(e==="v6"||!e)&&GM.test(t))}function nD(t,e){if(!BM.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function rD(t,e){return!!((e==="v4"||!e)&&KM.test(t)||(e==="v6"||!e)&&JM.test(t))}function oD(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,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 n in t.shape){let r=t.shape[n];e[n]=Ot.create(Es(r))}return new It({...t._def,shape:()=>e})}else return t instanceof tr?new tr({...t._def,type:Es(t.element)}):t instanceof Ot?Ot.create(Es(t.unwrap())):t instanceof Mn?Mn.create(Es(t.unwrap())):t instanceof Nn?Nn.create(t.items.map(e=>Es(e))):t}function Om(t,e){let n=An(t),r=An(e);if(t===e)return{valid:!0,data:t};if(n===z.object&&r===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=Om(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Yv(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Yv(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Rr.create()}var tn,Xv,re,LM,zM,HM,UM,FM,BM,ZM,qM,VM,Cm,WM,KM,GM,JM,XM,YM,Qv,QM,Pr,ho,go,yo,_o,Ts,bo,xo,Rr,er,fn,$s,tr,It,So,Qn,nu,vo,Nn,ru,Ps,Rs,ou,ko,wo,Eo,To,Cr,nn,Ot,Mn,$o,Po,Cs,sD,Ki,Gi,Ro,iD,N,aD,ok,sk,cD,uD,ik,lD,dD,pD,mD,fD,hD,gD,yD,_D,Im,bD,xD,SD,vD,kD,wD,ED,TD,$D,PD,RD,CD,OD,ID,AD,ND,MD,DD,jD,LD,zD,HD,UD,FD,ak=x(()=>{Yc();Qc();Jv();Rm();Vi();tn=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},Xv=(t,e)=>{if($r(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 n=new Ct(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return An(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:An(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new at,ctx:{common:e.parent.common,data:e.data,parsedType:An(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(ws(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Xv(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return $r(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>$r(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(ws(o)?o:Promise.resolve(o));return Xv(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:I.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new nn({schema:this,typeName:N.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:n=>this["~validate"](n)}}optional(){return Ot.create(this,this._def)}nullable(){return Mn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return tr.create(this)}promise(){return Cr.create(this,this._def)}or(e){return So.create([this,e],this._def)}and(e){return vo.create(this,e,this._def)}transform(e){return new nn({...te(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new $o({...te(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new Ki({typeName:N.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Po({...te(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Gi.create(this,e)}readonly(){return Ro.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},LM=/^c[^\s-]{8,}$/i,zM=/^[0-9a-z]+$/,HM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,UM=/^[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,FM=/^[a-z0-9_-]{21}$/i,BM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ZM=/^[-+]?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)?)??$/,qM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,VM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",WM=/^(?:(?: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])$/,KM=/^(?:(?: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])$/,GM=/^(([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]))$/,JM=/^(([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])$/,XM=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,YM=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qv="((\\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])))",QM=new RegExp(`^${Qv}$`);Pr=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_type,expected:z.string,received:s.parsedType}),G}let r=new at,o;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.lengthe.test(o),{validation:n,code:I.invalid_string,...B.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...B.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...B.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...B.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...B.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...B.errToObj(n)})}nonempty(e){return this.min(1,B.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew Pr({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...te(t)});ho=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)!==z.number){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_type,expected:z.number,received:s.parsedType}),G}let r,o=new at;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?oD(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:I.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuee.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.valuenew ho({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...te(t)});go=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)!==z.bigint)return this._getInvalidInput(e);let r,o=new at;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.bigint,received:n.parsedType}),G}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew go({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...te(t)});yo=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.boolean,received:r.parsedType}),G}return gt(e.data)}};yo.create=t=>new yo({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...te(t)});_o=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_type,expected:z.date,received:s.parsedType}),G}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_date}),G}let r=new at,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ce.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:B.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:B.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew _o({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...te(t)});Ts=class extends re{_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.symbol,received:r.parsedType}),G}return gt(e.data)}};Ts.create=t=>new Ts({typeName:N.ZodSymbol,...te(t)});bo=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.undefined,received:r.parsedType}),G}return gt(e.data)}};bo.create=t=>new bo({typeName:N.ZodUndefined,...te(t)});xo=class extends re{_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.null,received:r.parsedType}),G}return gt(e.data)}};xo.create=t=>new xo({typeName:N.ZodNull,...te(t)});Rr=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return gt(e.data)}};Rr.create=t=>new Rr({typeName:N.ZodAny,...te(t)});er=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gt(e.data)}};er.create=t=>new er({typeName:N.ZodUnknown,...te(t)});fn=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.never,received:n.parsedType}),G}};fn.create=t=>new fn({typeName:N.ZodNever,...te(t)});$s=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.void,received:r.parsedType}),G}return gt(e.data)}};$s.create=t=>new $s({typeName:N.ZodVoid,...te(t)});tr=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==z.array)return D(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),G;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.lengtho.maxLength.value&&(D(n,{code:I.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new tn(n,i,n.path,a)))).then(i=>at.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new tn(n,i,n.path,a)));return at.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:B.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};tr.create=(t,e)=>new tr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...te(e)});It=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(),n=ce.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return D(u,{code:I.invalid_type,expected:z.object,received:u.parsedType}),G}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof fn&&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 tn(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof fn){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&&(D(o,{code:I.unrecognized_keys,keys:a}),r.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 tn(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,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>at.mergeObjectSync(r,u)):at.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return B.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:B.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:N.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ce.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ce.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Es(this)}partial(e){let n={};for(let r of ce.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ce.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ot;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return nk(ce.objectKeys(this.shape))}};It.create=(t,e)=>new It({shape:()=>t,unknownKeys:"strip",catchall:fn.create(),typeName:N.ZodObject,...te(e)});It.strictCreate=(t,e)=>new It({shape:()=>t,unknownKeys:"strict",catchall:fn.create(),typeName:N.ZodObject,...te(e)});It.lazycreate=(t,e)=>new It({shape:t,unknownKeys:"strip",catchall:fn.create(),typeName:N.ZodObject,...te(e)});So=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ct(a.ctx.common.issues));return D(n,{code:I.invalid_union,unionErrors:i}),G}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.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 n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ct(c));return D(n,{code:I.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};So.create=(t,e)=>new So({options:t,typeName:N.ZodUnion,...te(e)});Qn=t=>t instanceof ko?Qn(t.schema):t instanceof nn?Qn(t.innerType()):t instanceof wo?[t.value]:t instanceof Eo?t.options:t instanceof To?ce.objectValues(t.enum):t instanceof $o?Qn(t._def.innerType):t instanceof bo?[void 0]:t instanceof xo?[null]:t instanceof Ot?[void 0,...Qn(t.unwrap())]:t instanceof Mn?[null,...Qn(t.unwrap())]:t instanceof Ki||t instanceof Ro?Qn(t.unwrap()):t instanceof Po?Qn(t._def.innerType):[],nu=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return D(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),G;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(D(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=Qn(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:N.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...te(r)})}};vo=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(eu(s)||eu(i))return G;let a=Om(s.value,i.value);return a.valid?((tu(s)||tu(i))&&n.dirty(),{status:n.value,value:a.data}):(D(r,{code:I.invalid_intersection_types}),G)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};vo.create=(t,e,n)=>new vo({left:t,right:e,typeName:N.ZodIntersection,...te(n)});Nn=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return D(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),G;if(r.data.lengththis._def.items.length&&(D(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new tn(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>at.mergeArray(n,i)):at.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Nn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:t,typeName:N.ZodTuple,rest:null,...te(e)})};ru=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return D(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),G;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new tn(r,a,r.path,a)),value:i._parse(new tn(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?at.mergeObjectAsync(n,o):at.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:N.ZodRecord,...te(r)}):new t({keyType:Pr.create(),valueType:e,typeName:N.ZodRecord,...te(n)})}},Ps=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return D(r,{code:I.invalid_type,expected:z.map,received:r.parsedType}),G;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new tn(r,a,r.path,[u,"key"])),value:s._parse(new tn(r,c,r.path,[u,"value"]))}));if(r.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Ps.create=(t,e,n)=>new Ps({valueType:e,keyType:t,typeName:N.ZodMap,...te(n)});Rs=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return D(r,{code:I.invalid_type,expected:z.set,received:r.parsedType}),G;let o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(D(r,{code:I.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return G;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new tn(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:B.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Rs.create=(t,e)=>new Rs({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...te(e)});ou=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.function)return D(n,{code:I.invalid_type,expected:z.function,received:n.parsedType}),G;function r(a,c){return Wi({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ks(),Yn].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function o(a,c){return Wi({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ks(),Yn].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Cr){let a=this;return gt(async function(...c){let u=new Ct([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(r(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return gt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ct([r(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:Nn.create(e).rest(er.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,n,r){return new t({args:e||Nn.create([]).rest(er.create()),returns:n||er.create(),typeName:N.ZodFunction,...te(r)})}},ko=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};ko.create=(t,e)=>new ko({getter:t,typeName:N.ZodLazy,...te(e)});wo=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return D(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};wo.create=(t,e)=>new wo({value:t,typeName:N.ZodLiteral,...te(e)});Eo=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{expected:ce.joinValues(r),received:n.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{received:n.data,code:I.invalid_enum_value,options:r}),G}return gt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Eo.create=nk;To=class extends re{_parse(e){let n=ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let o=ce.objectValues(n);return D(r,{expected:ce.joinValues(o),received:r.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(n);return D(r,{received:r.data,code:I.invalid_enum_value,options:o}),G}return gt(e.data)}get enum(){return this._def.values}};To.create=(t,e)=>new To({values:t,typeName:N.ZodNativeEnum,...te(e)});Cr=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.promise&&n.common.async===!1)return D(n,{code:I.invalid_type,expected:z.promise,received:n.parsedType}),G;let r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return gt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Cr.create=(t,e)=>new Cr({type:t,typeName:N.ZodPromise,...te(e)});nn=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{D(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?G:c.status==="dirty"?fo(c.value):n.value==="dirty"?fo(c.value):c});{if(n.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?G:a.status==="dirty"?fo(a.value):n.value==="dirty"?fo(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!$r(i))return G;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>$r(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):G);ce.assertNever(o)}};nn.create=(t,e,n)=>new nn({schema:t,typeName:N.ZodEffects,effect:e,...te(n)});nn.createWithPreprocess=(t,e,n)=>new nn({schema:e,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...te(n)});Ot=class extends re{_parse(e){return this._getType(e)===z.undefined?gt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:N.ZodOptional,...te(e)});Mn=class extends re{_parse(e){return this._getType(e)===z.null?gt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mn.create=(t,e)=>new Mn({innerType:t,typeName:N.ZodNullable,...te(e)});$o=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$o.create=(t,e)=>new $o({innerType:t,typeName:N.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Po=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ws(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ct(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ct(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Po.create=(t,e)=>new Po({innerType:t,typeName:N.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Cs=class extends re{_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.nan,received:r.parsedType}),G}return{status:"valid",value:e.data}}};Cs.create=t=>new Cs({typeName:N.ZodNaN,...te(t)});sD=Symbol("zod_brand"),Ki=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Gi=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?G:s.status==="dirty"?(n.dirty(),fo(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?G:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:N.ZodPipeline})}},Ro=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=o=>($r(o)&&(o.value=Object.freeze(o.value)),o);return ws(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:N.ZodReadonly,...te(e)});iD={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"})(N||(N={}));aD=(t,e={message:`Input not instance of ${t.name}`})=>rk(n=>n instanceof t,e),ok=Pr.create,sk=ho.create,cD=Cs.create,uD=go.create,ik=yo.create,lD=_o.create,dD=Ts.create,pD=bo.create,mD=xo.create,fD=Rr.create,hD=er.create,gD=fn.create,yD=$s.create,_D=tr.create,Im=It.create,bD=It.strictCreate,xD=So.create,SD=nu.create,vD=vo.create,kD=Nn.create,wD=ru.create,ED=Ps.create,TD=Rs.create,$D=ou.create,PD=ko.create,RD=wo.create,CD=Eo.create,OD=To.create,ID=Cr.create,AD=nn.create,ND=Ot.create,MD=Mn.create,DD=nn.createWithPreprocess,jD=Gi.create,LD=()=>ok().optional(),zD=()=>sk().optional(),HD=()=>ik().optional(),UD={string:(t=>Pr.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}))},FD=G});var j={};_e(j,{BRAND:()=>sD,DIRTY:()=>fo,EMPTY_PATH:()=>jM,INVALID:()=>G,NEVER:()=>FD,OK:()=>gt,ParseStatus:()=>at,Schema:()=>re,ZodAny:()=>Rr,ZodArray:()=>tr,ZodBigInt:()=>go,ZodBoolean:()=>yo,ZodBranded:()=>Ki,ZodCatch:()=>Po,ZodDate:()=>_o,ZodDefault:()=>$o,ZodDiscriminatedUnion:()=>nu,ZodEffects:()=>nn,ZodEnum:()=>Eo,ZodError:()=>Ct,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>ou,ZodIntersection:()=>vo,ZodIssueCode:()=>I,ZodLazy:()=>ko,ZodLiteral:()=>wo,ZodMap:()=>Ps,ZodNaN:()=>Cs,ZodNativeEnum:()=>To,ZodNever:()=>fn,ZodNull:()=>xo,ZodNullable:()=>Mn,ZodNumber:()=>ho,ZodObject:()=>It,ZodOptional:()=>Ot,ZodParsedType:()=>z,ZodPipeline:()=>Gi,ZodPromise:()=>Cr,ZodReadonly:()=>Ro,ZodRecord:()=>ru,ZodSchema:()=>re,ZodSet:()=>Rs,ZodString:()=>Pr,ZodSymbol:()=>Ts,ZodTransformer:()=>nn,ZodTuple:()=>Nn,ZodType:()=>re,ZodUndefined:()=>bo,ZodUnion:()=>So,ZodUnknown:()=>er,ZodVoid:()=>$s,addIssueToContext:()=>D,any:()=>fD,array:()=>_D,bigint:()=>uD,boolean:()=>ik,coerce:()=>UD,custom:()=>rk,date:()=>lD,datetimeRegex:()=>tk,defaultErrorMap:()=>Yn,discriminatedUnion:()=>SD,effect:()=>AD,enum:()=>CD,function:()=>$D,getErrorMap:()=>ks,getParsedType:()=>An,instanceof:()=>aD,intersection:()=>vD,isAborted:()=>eu,isAsync:()=>ws,isDirty:()=>tu,isValid:()=>$r,late:()=>iD,lazy:()=>PD,literal:()=>RD,makeIssue:()=>Wi,map:()=>ED,nan:()=>cD,nativeEnum:()=>OD,never:()=>gD,null:()=>mD,nullable:()=>MD,number:()=>sk,object:()=>Im,objectUtil:()=>$m,oboolean:()=>HD,onumber:()=>zD,optional:()=>ND,ostring:()=>LD,pipeline:()=>jD,preprocess:()=>DD,promise:()=>ID,quotelessJson:()=>NM,record:()=>wD,set:()=>TD,setErrorMap:()=>DM,strictObject:()=>bD,string:()=>ok,symbol:()=>dD,transformer:()=>AD,tuple:()=>kD,undefined:()=>pD,union:()=>xD,unknown:()=>hD,util:()=>ce,void:()=>yD});var su=x(()=>{Qc();Rm();Gv();Vi();ak();Yc()});var Ji=x(()=>{su()});function E(t,e,n){function r(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=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Ft(t){return t&&Object.assign(iu,t),iu}var ZD,nr,iu,Os=x(()=>{ZD=Object.freeze({status:"aborted"});nr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},iu={}});var ue={};_e(ue,{BIGINT_FORMAT_RANGES:()=>uk,Class:()=>Nm,NUMBER_FORMAT_RANGES:()=>Um,aborted:()=>Oo,allowsEval:()=>Lm,assert:()=>GD,assertEqual:()=>qD,assertIs:()=>WD,assertNever:()=>KD,assertNotEqual:()=>VD,assignProp:()=>jm,cached:()=>Qi,captureStackTrace:()=>cu,cleanEnum:()=>cj,cleanRegex:()=>ta,clone:()=>Bt,createTransparentProxy:()=>tj,defineLazy:()=>$e,esc:()=>Co,escapeRegex:()=>Or,extend:()=>oj,finalizeIssue:()=>hn,floatSafeRemainder:()=>Dm,getElementAtPath:()=>JD,getEnumValues:()=>Yi,getLengthableOrigin:()=>na,getParsedType:()=>ej,getSizableOrigin:()=>lk,isObject:()=>Is,isPlainObject:()=>As,issue:()=>Fm,joinValues:()=>au,jsonStringifyReplacer:()=>Mm,merge:()=>sj,normalizeParams:()=>J,nullish:()=>ea,numKeys:()=>QD,omit:()=>rj,optionalKeys:()=>Hm,partial:()=>ij,pick:()=>nj,prefixIssues:()=>Dn,primitiveTypes:()=>ck,promiseAllObject:()=>XD,propertyKeyTypes:()=>zm,randomString:()=>YD,required:()=>aj,stringifyPrimitive:()=>uu,unwrapMessage:()=>Xi});function qD(t){return t}function VD(t){return t}function WD(t){}function KD(t){throw new Error}function GD(t){}function Yi(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function au(t,e="|"){return t.map(n=>uu(n)).join(e)}function Mm(t,e){return typeof e=="bigint"?e.toString():e}function Qi(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ea(t){return t==null}function ta(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Dm(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function $e(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function jm(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function JD(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function XD(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;se};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 tj(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function uu(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Hm(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function nj(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return Bt(t,{...t._zod.def,shape:n,checks:[]})}function rj(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return Bt(t,{...t._zod.def,shape:n,checks:[]})}function oj(t,e){if(!As(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return jm(this,"shape",r),r},checks:[]};return Bt(t,n)}function sj(t,e){return Bt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return jm(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function ij(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return Bt(e,{...e._zod.def,shape:o,checks:[]})}function aj(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return Bt(e,{...e._zod.def,shape:o,checks:[]})}function Oo(t,e=0){for(let n=e;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Xi(t){return typeof t=="string"?t:t?.message}function hn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=Xi(t.inst?._zod.def?.error?.(t))??Xi(e?.error?.(t))??Xi(n.customError?.(t))??Xi(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function lk(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function na(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Fm(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function cj(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var cu,Lm,ej,zm,ck,Um,uk,Nm,jn=x(()=>{cu=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Lm=Qi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});ej=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}`)}},zm=new Set(["string","number","symbol"]),ck=new Set(["string","number","bigint","boolean","symbol","undefined"]);Um={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]},uk={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Nm=class{constructor(...e){}}});function Bm(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function Zm(t,e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;c{Os();jn();dk=(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,Mm,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},lu=E("$ZodError",dk),ra=E("$ZodError",dk,{Parent:Error})});var Vm,Wm,Km,Gm,Jm,Io,Xm,Ao,Ym=x(()=>{Os();qm();jn();Vm=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new nr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>hn(c,s,Ft())));throw cu(a,o?.callee),a}return i.value},Wm=Vm(ra),Km=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>hn(c,s,Ft())));throw cu(a,o?.callee),a}return i.value},Gm=Km(ra),Jm=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new nr;return s.issues.length?{success:!1,error:new(t??lu)(s.issues.map(i=>hn(i,o,Ft())))}:{success:!0,data:s.value}},Io=Jm(ra),Xm=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>hn(i,o,Ft())))}:{success:!0,data:s.value}},Ao=Xm(ra)});function Sk(){return new RegExp(lj,"u")}function Ok(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 Ik(t){return new RegExp(`^${Ok(t)}$`)}function Ak(t){let e=Ok({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Rk}T(?:${r})$`)}var pk,mk,fk,hk,gk,yk,_k,bk,Qm,xk,lj,vk,kk,wk,Ek,Tk,ef,$k,Pk,Rk,Ck,Nk,Mk,Dk,jk,Lk,zk,Hk,pu=x(()=>{pk=/^[cC][^\s-]{8,}$/,mk=/^[0-9a-z]+$/,fk=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,hk=/^[0-9a-vA-V]{20}$/,gk=/^[A-Za-z0-9]{27}$/,yk=/^[a-zA-Z0-9_-]{21}$/,_k=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bk=/^([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})$/,Qm=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)$/,xk=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,lj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";vk=/^(?:(?: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])$/,kk=/^(([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})$/,wk=/^((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])$/,Ek=/^(([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])$/,Tk=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ef=/^[A-Za-z0-9_-]*$/,$k=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Pk=/^\+(?:[0-9]){6,14}[0-9]$/,Rk="(?:(?:\\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])))",Ck=new RegExp(`^${Rk}$`);Nk=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Mk=/^\d+$/,Dk=/^-?\d+(?:\.\d+)?/i,jk=/true|false/i,Lk=/null/i,zk=/^[^A-Z]*$/,Hk=/^[^a-z]*$/});var ct,Uk,tf,nf,Fk,Bk,Zk,qk,Vk,oa,Wk,Kk,Gk,Jk,Xk,Yk,Qk,mu=x(()=>{Os();pu();jn();ct=E("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Uk={number:"number",bigint:"bigint",object:"date"},tf=E("$ZodCheckLessThan",(t,e)=>{ct.init(t,e);let n=Uk[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?r.value<=e.value:r.value{ct.init(t,e);let n=Uk[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fk=E("$ZodCheckMultipleOf",(t,e)=>{ct.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Dm(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Bk=E("$ZodCheckNumberFormat",(t,e)=>{ct.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Um[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Mk)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,continue:!e.abort});return}}as&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Zk=E("$ZodCheckMaxLength",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ea(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let o=r.value;if(o.length<=e.maximum)return;let i=na(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qk=E("$ZodCheckMinLength",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ea(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=na(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Vk=E("$ZodCheckLengthEquals",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ea(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=na(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),oa=E("$ZodCheckStringFormat",(t,e)=>{var n,r;ct.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),Wk=E("$ZodCheckRegex",(t,e)=>{oa.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Kk=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=zk),oa.init(t,e)}),Gk=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Hk),oa.init(t,e)}),Jk=E("$ZodCheckIncludes",(t,e)=>{ct.init(t,e);let n=Or(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),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})}}),Xk=E("$ZodCheckStartsWith",(t,e)=>{ct.init(t,e);let n=new RegExp(`^${Or(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Yk=E("$ZodCheckEndsWith",(t,e)=>{ct.init(t,e);let n=new RegExp(`.*${Or(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),Qk=E("$ZodCheckOverwrite",(t,e)=>{ct.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var fu,rf=x(()=>{fu=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 r=e.split(` +`);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#m(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u0?n.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))){r.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.#F(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;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])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;lo&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}}});import{readFileSync as tk,realpathSync as Om}from"node:fs";import{relative as TM,resolve as mo,sep as $M}from"node:path";function nk(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function PM(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function RM(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function ek(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function CM(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=RM(o),a=ek(s);n=`^${i}(\\s${a})?$`}else n=`^${ek(t)}$`;return new RegExp(n,e?"i":"")}function OM(t,e=!1){let n="",r=0;for(;r=0&&t[r]==="\\";r--)n++;return n%2===1}function AM(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===` +`||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function ok(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),p=t.slice(d,c);e.push(p)}}}return e}function sk(t){let e=[],n=AM(t);for(let r of n){e.push(r);for(let o of ok(r))e.push(...sk(o))}return e}function Cm(t){let e;try{e=tk(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&nk(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function Im(t,e){let n=[];if(t){let o=mo(t,".claude","settings.local.json"),s=Cm(o);s&&n.push(s);let i=mo(t,".claude","settings.json"),a=Cm(i);a&&n.push(a)}let r=e!==void 0?[e]:km();for(let o of r){let s=Cm(o);s&&n.push(s)}return n}function fo(t,e,n){return Am(t,"deny",e,n)}function Am(t,e,n,r){let o=[],s=a=>{let c;try{c=tk(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.[e];if(!Array.isArray(l))return[];let d=[];for(let p of l){if(typeof p!="string")continue;let f=PM(p);f&&f.tool===t&&d.push(f.glob)}return d};if(n){let a=s(mo(n,".claude","settings.local.json"));a!==null&&o.push(a);let c=s(mo(n,".claude","settings.json"));c!==null&&o.push(c)}let i=r!==void 0?[r]:km();for(let a of i){let c=s(a);c!==null&&o.push(c)}return o}function Nm(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=sk(t);for(let o of r)for(let s of e){let i=IM(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Tr(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=mo(r,t);s.add(o(i));try{s.add(o(Om(i)))}catch{}}for(let i of e)for(let a of i){let c=OM(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function NM(t,e,n=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let r=mo(e),o=mo(e,t),s=(i,a)=>{let c=i,u=a;if(n&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=TM(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+$M)||MM(l))};if(!s(r,o))return!1;try{let i=Om(r),a=Om(o);if(!s(i,a))return!1}catch{}return!0}function MM(t){if(t.startsWith("/"))return!0;if(t.length>=3&&t[1]===":"&&(t[2]==="\\"||t[2]==="/")){let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122}return!1}function ik(t,e,n=[],r=process.platform==="win32"||process.platform==="darwin"){return NM(t,e,r)?{allowed:!0,reason:"inside"}:n.some(o=>o.length>0)&&Tr(t,n,r,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}function jM(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function ak(t,e){let n=DM[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...jM(t)),r}var DM,Mm=x(()=>{"use strict";vr();DM={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 lk={};ye(lk,{healClaudeJsonMcpArgs:()=>YM,healInstalledPlugins:()=>GM,healMcpJsonArgs:()=>XM,healPluginJsonMcpServers:()=>tu,healSettingsEnabledPlugins:()=>JM,sweepStaleMcpJson:()=>nu});import{existsSync as Xn,readFileSync as ws,writeFileSync as Ki,readdirSync as VM,unlinkSync as WM,statSync as KM}from"node:fs";import{resolve as St,sep as ho}from"node:path";function GM({registryPath:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!Xn(t))return{healed:[],skipped:"no-registry"};let r;try{r=ws(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(r)}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[n]||[];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)+ho;if(!l.startsWith(d))continue;let p=St(u,".claude-plugin","plugin.json");if(!Xn(p))continue;let f=null;try{let m=JSON.parse(ws(p,"utf-8"));m&&typeof m.version=="string"&&m.version&&(f=m.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[n];(c==null||c===!1||c==="")&&(o.enabledPlugins[n]=!0,i.push("enabled-plugins"))}if(i.length>0)try{Ki(t,JSON.stringify(o,null,2)+` +`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function JM({settingsPath:t,pluginKey:e}){if(!t||!Xn(t))return{healed:[],skipped:"no-settings"};let n;try{n=ws(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let r;try{r=JSON.parse(n)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!r.enabledPlugins||typeof r.enabledPlugins!="object"||Array.isArray(r.enabledPlugins))&&(r.enabledPlugins={});let s=r.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(r.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{Ki(t,JSON.stringify(r,null,2)+` +`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function tu({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=St(t),o=St(e)+ho;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=St(t,".claude-plugin","plugin.json");if(!Xn(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=ws(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=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,f=p.map(h=>typeof h!="string"||h===Wi?h:/[/\\]start\.mjs$/.test(h)?Wi:h);if(f.some((h,g)=>h!==p[g])){l.args=f,d.push("plugin-json-args");try{Ki(s,JSON.stringify(a,null,2)+` +`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function XM({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=St(t),o=St(e)+ho;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=St(t,".mcp.json");if(!Xn(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=ws(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=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,f=p.map(h=>typeof h!="string"||h===Wi?h:h==="./start.mjs"||h==="start.mjs"||/[/\\]start\.mjs$/.test(h)?Wi:h);if(f.some((h,g)=>h!==p[g])){l.args=f,d.push("mcp-json-args");try{Ki(s,JSON.stringify(a,null,2)+` +`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function YM({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:n}){if(!t||!Xn(t))return{healed:[],skipped:"no-claude-json"};let r;try{r=ws(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(r)}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(n),c=a+ho,u=!1;for(let l of Object.values(s))if(!(!l||typeof l!="object"||!Array.isArray(l.args)))for(let d=0;d{"use strict";Wi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,jm,z,In,Gi=x(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,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 r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(jm||(jm={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),In=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 I,tD,Ct,ru=x(()=>{Gi();I=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"]),tD=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=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;cn.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Ct.create=t=>new Ct(t)});var nD,Yn,Lm=x(()=>{ru();Gi();nD=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===z.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ce.assertNever(t)}return{message:n}},Yn=nD});function rD(t){pk=t}function Es(){return pk}var pk,ou=x(()=>{Lm();pk=Yn});function D(t,e){let n=Es(),r=Ji({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Yn?void 0:Yn].filter(o=>!!o)});t.common.issues.push(r)}var Ji,oD,ct,G,go,gt,su,iu,$r,Ts,zm=x(()=>{ou();Lm();Ji=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},oD=[];ct=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return G;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return G;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},G=Object.freeze({status:"aborted"}),go=t=>({status:"dirty",value:t}),gt=t=>({status:"valid",value:t}),su=t=>t.status==="aborted",iu=t=>t.status==="dirty",$r=t=>t.status==="valid",Ts=t=>typeof Promise<"u"&&t instanceof Promise});var mk=x(()=>{});var B,fk=x(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function _k(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function vD(t){return new RegExp(`^${_k(t)}$`)}function bk(t){let e=`${yk}T${_k(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function SD(t,e){return!!((e==="v4"||!e)&&fD.test(t)||(e==="v6"||!e)&&gD.test(t))}function kD(t,e){if(!lD.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function wD(t,e){return!!((e==="v4"||!e)&&hD.test(t)||(e==="v6"||!e)&&yD.test(t))}function ED(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function $s(t){if(t instanceof It){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Ot.create($s(r))}return new It({...t._def,shape:()=>e})}else return t instanceof tr?new tr({...t._def,type:$s(t.element)}):t instanceof Ot?Ot.create($s(t.unwrap())):t instanceof Nn?Nn.create($s(t.unwrap())):t instanceof An?An.create(t.items.map(e=>$s(e))):t}function Um(t,e){let n=In(t),r=In(e);if(t===e)return{valid:!0,data:t};if(n===z.object&&r===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=Um(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=gk(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=gk(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Rr.create()}var tn,hk,re,sD,iD,aD,cD,uD,lD,dD,pD,mD,Hm,fD,hD,gD,yD,_D,bD,yk,xD,Pr,yo,_o,bo,xo,Ps,vo,So,Rr,er,mn,Rs,tr,It,ko,Qn,au,wo,An,cu,Cs,Os,uu,Eo,To,$o,Po,Cr,nn,Ot,Nn,Ro,Co,Is,TD,Xi,Yi,Oo,$D,N,PD,Sk,kk,RD,CD,wk,OD,ID,AD,ND,MD,DD,jD,LD,zD,Fm,HD,UD,FD,BD,ZD,qD,VD,WD,KD,GD,JD,XD,YD,QD,ej,tj,nj,rj,oj,sj,ij,aj,cj,uj,Ek=x(()=>{ru();ou();fk();zm();Gi();tn=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},hk=(t,e)=>{if($r(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 n=new Ct(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return In(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:In(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ct,ctx:{common:e.parent.common,data:e.data,parsedType:In(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Ts(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:In(e)},o=this._parseSync({data:e,path:r.path,parent:r});return hk(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:In(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return $r(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>$r(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:In(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(Ts(o)?o:Promise.resolve(o));return hk(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:I.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new nn({schema:this,typeName:N.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:n=>this["~validate"](n)}}optional(){return Ot.create(this,this._def)}nullable(){return Nn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return tr.create(this)}promise(){return Cr.create(this,this._def)}or(e){return ko.create([this,e],this._def)}and(e){return wo.create(this,e,this._def)}transform(e){return new nn({...te(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Ro({...te(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new Xi({typeName:N.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Co({...te(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Yi.create(this,e)}readonly(){return Oo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},sD=/^c[^\s-]{8,}$/i,iD=/^[0-9a-z]+$/,aD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cD=/^[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,uD=/^[a-z0-9_-]{21}$/i,lD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,dD=/^[-+]?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)?)??$/,pD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,mD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",fD=/^(?:(?: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])$/,hD=/^(?:(?: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])$/,gD=/^(([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]))$/,yD=/^(([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])$/,_D=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yk="((\\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])))",xD=new RegExp(`^${yk}$`);Pr=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_type,expected:z.string,received:s.parsedType}),G}let r=new ct,o;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.lengthe.test(o),{validation:n,code:I.invalid_string,...B.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...B.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...B.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...B.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...B.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...B.errToObj(n)})}nonempty(e){return this.min(1,B.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew Pr({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...te(t)});yo=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)!==z.number){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_type,expected:z.number,received:s.parsedType}),G}let r,o=new ct;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ED(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:I.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuee.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.valuenew yo({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...te(t)});_o=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)!==z.bigint)return this._getInvalidInput(e);let r,o=new ct;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),D(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.bigint,received:n.parsedType}),G}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew _o({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...te(t)});bo=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.boolean,received:r.parsedType}),G}return gt(e.data)}};bo.create=t=>new bo({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...te(t)});xo=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_type,expected:z.date,received:s.parsedType}),G}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return D(s,{code:I.invalid_date}),G}let r=new ct,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ce.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:B.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:B.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew xo({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...te(t)});Ps=class extends re{_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.symbol,received:r.parsedType}),G}return gt(e.data)}};Ps.create=t=>new Ps({typeName:N.ZodSymbol,...te(t)});vo=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.undefined,received:r.parsedType}),G}return gt(e.data)}};vo.create=t=>new vo({typeName:N.ZodUndefined,...te(t)});So=class extends re{_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.null,received:r.parsedType}),G}return gt(e.data)}};So.create=t=>new So({typeName:N.ZodNull,...te(t)});Rr=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return gt(e.data)}};Rr.create=t=>new Rr({typeName:N.ZodAny,...te(t)});er=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gt(e.data)}};er.create=t=>new er({typeName:N.ZodUnknown,...te(t)});mn=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.never,received:n.parsedType}),G}};mn.create=t=>new mn({typeName:N.ZodNever,...te(t)});Rs=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.void,received:r.parsedType}),G}return gt(e.data)}};Rs.create=t=>new Rs({typeName:N.ZodVoid,...te(t)});tr=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==z.array)return D(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),G;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.lengtho.maxLength.value&&(D(n,{code:I.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new tn(n,i,n.path,a)))).then(i=>ct.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new tn(n,i,n.path,a)));return ct.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:B.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};tr.create=(t,e)=>new tr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...te(e)});It=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(),n=ce.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return D(u,{code:I.invalid_type,expected:z.object,received:u.parsedType}),G}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mn&&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 tn(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mn){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&&(D(o,{code:I.unrecognized_keys,keys:a}),r.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 tn(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,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>ct.mergeObjectSync(r,u)):ct.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return B.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:B.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:N.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ce.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ce.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return $s(this)}partial(e){let n={};for(let r of ce.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ce.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ot;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return xk(ce.objectKeys(this.shape))}};It.create=(t,e)=>new It({shape:()=>t,unknownKeys:"strip",catchall:mn.create(),typeName:N.ZodObject,...te(e)});It.strictCreate=(t,e)=>new It({shape:()=>t,unknownKeys:"strict",catchall:mn.create(),typeName:N.ZodObject,...te(e)});It.lazycreate=(t,e)=>new It({shape:t,unknownKeys:"strip",catchall:mn.create(),typeName:N.ZodObject,...te(e)});ko=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ct(a.ctx.common.issues));return D(n,{code:I.invalid_union,unionErrors:i}),G}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.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 n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ct(c));return D(n,{code:I.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};ko.create=(t,e)=>new ko({options:t,typeName:N.ZodUnion,...te(e)});Qn=t=>t instanceof Eo?Qn(t.schema):t instanceof nn?Qn(t.innerType()):t instanceof To?[t.value]:t instanceof $o?t.options:t instanceof Po?ce.objectValues(t.enum):t instanceof Ro?Qn(t._def.innerType):t instanceof vo?[void 0]:t instanceof So?[null]:t instanceof Ot?[void 0,...Qn(t.unwrap())]:t instanceof Nn?[null,...Qn(t.unwrap())]:t instanceof Xi||t instanceof Oo?Qn(t.unwrap()):t instanceof Co?Qn(t._def.innerType):[],au=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return D(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),G;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(D(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=Qn(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:N.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...te(r)})}};wo=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(su(s)||su(i))return G;let a=Um(s.value,i.value);return a.valid?((iu(s)||iu(i))&&n.dirty(),{status:n.value,value:a.data}):(D(r,{code:I.invalid_intersection_types}),G)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};wo.create=(t,e,n)=>new wo({left:t,right:e,typeName:N.ZodIntersection,...te(n)});An=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return D(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),G;if(r.data.lengththis._def.items.length&&(D(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new tn(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ct.mergeArray(n,i)):ct.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};An.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new An({items:t,typeName:N.ZodTuple,rest:null,...te(e)})};cu=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return D(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),G;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new tn(r,a,r.path,a)),value:i._parse(new tn(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ct.mergeObjectAsync(n,o):ct.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:N.ZodRecord,...te(r)}):new t({keyType:Pr.create(),valueType:e,typeName:N.ZodRecord,...te(n)})}},Cs=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return D(r,{code:I.invalid_type,expected:z.map,received:r.parsedType}),G;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new tn(r,a,r.path,[u,"key"])),value:s._parse(new tn(r,c,r.path,[u,"value"]))}));if(r.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Cs.create=(t,e,n)=>new Cs({valueType:e,keyType:t,typeName:N.ZodMap,...te(n)});Os=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return D(r,{code:I.invalid_type,expected:z.set,received:r.parsedType}),G;let o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(D(r,{code:I.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return G;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new tn(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:B.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Os.create=(t,e)=>new Os({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...te(e)});uu=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.function)return D(n,{code:I.invalid_type,expected:z.function,received:n.parsedType}),G;function r(a,c){return Ji({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Es(),Yn].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function o(a,c){return Ji({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Es(),Yn].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Cr){let a=this;return gt(async function(...c){let u=new Ct([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(r(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return gt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ct([r(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:An.create(e).rest(er.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,n,r){return new t({args:e||An.create([]).rest(er.create()),returns:n||er.create(),typeName:N.ZodFunction,...te(r)})}},Eo=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Eo.create=(t,e)=>new Eo({getter:t,typeName:N.ZodLazy,...te(e)});To=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return D(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};To.create=(t,e)=>new To({value:t,typeName:N.ZodLiteral,...te(e)});$o=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{expected:ce.joinValues(r),received:n.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{received:n.data,code:I.invalid_enum_value,options:r}),G}return gt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};$o.create=xk;Po=class extends re{_parse(e){let n=ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let o=ce.objectValues(n);return D(r,{expected:ce.joinValues(o),received:r.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(n);return D(r,{received:r.data,code:I.invalid_enum_value,options:o}),G}return gt(e.data)}get enum(){return this._def.values}};Po.create=(t,e)=>new Po({values:t,typeName:N.ZodNativeEnum,...te(e)});Cr=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.promise&&n.common.async===!1)return D(n,{code:I.invalid_type,expected:z.promise,received:n.parsedType}),G;let r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return gt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Cr.create=(t,e)=>new Cr({type:t,typeName:N.ZodPromise,...te(e)});nn=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{D(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?G:c.status==="dirty"?go(c.value):n.value==="dirty"?go(c.value):c});{if(n.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?G:a.status==="dirty"?go(a.value):n.value==="dirty"?go(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!$r(i))return G;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>$r(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):G);ce.assertNever(o)}};nn.create=(t,e,n)=>new nn({schema:t,typeName:N.ZodEffects,effect:e,...te(n)});nn.createWithPreprocess=(t,e,n)=>new nn({schema:e,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...te(n)});Ot=class extends re{_parse(e){return this._getType(e)===z.undefined?gt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:N.ZodOptional,...te(e)});Nn=class extends re{_parse(e){return this._getType(e)===z.null?gt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Nn.create=(t,e)=>new Nn({innerType:t,typeName:N.ZodNullable,...te(e)});Ro=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:N.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Co=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ts(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ct(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ct(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Co.create=(t,e)=>new Co({innerType:t,typeName:N.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Is=class extends re{_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.nan,received:r.parsedType}),G}return{status:"valid",value:e.data}}};Is.create=t=>new Is({typeName:N.ZodNaN,...te(t)});TD=Symbol("zod_brand"),Xi=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Yi=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?G:s.status==="dirty"?(n.dirty(),go(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?G:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:N.ZodPipeline})}},Oo=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=o=>($r(o)&&(o.value=Object.freeze(o.value)),o);return Ts(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Oo.create=(t,e)=>new Oo({innerType:t,typeName:N.ZodReadonly,...te(e)});$D={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"})(N||(N={}));PD=(t,e={message:`Input not instance of ${t.name}`})=>vk(n=>n instanceof t,e),Sk=Pr.create,kk=yo.create,RD=Is.create,CD=_o.create,wk=bo.create,OD=xo.create,ID=Ps.create,AD=vo.create,ND=So.create,MD=Rr.create,DD=er.create,jD=mn.create,LD=Rs.create,zD=tr.create,Fm=It.create,HD=It.strictCreate,UD=ko.create,FD=au.create,BD=wo.create,ZD=An.create,qD=cu.create,VD=Cs.create,WD=Os.create,KD=uu.create,GD=Eo.create,JD=To.create,XD=$o.create,YD=Po.create,QD=Cr.create,ej=nn.create,tj=Ot.create,nj=Nn.create,rj=nn.createWithPreprocess,oj=Yi.create,sj=()=>Sk().optional(),ij=()=>kk().optional(),aj=()=>wk().optional(),cj={string:(t=>Pr.create({...t,coerce:!0})),number:(t=>yo.create({...t,coerce:!0})),boolean:(t=>bo.create({...t,coerce:!0})),bigint:(t=>_o.create({...t,coerce:!0})),date:(t=>xo.create({...t,coerce:!0}))},uj=G});var j={};ye(j,{BRAND:()=>TD,DIRTY:()=>go,EMPTY_PATH:()=>oD,INVALID:()=>G,NEVER:()=>uj,OK:()=>gt,ParseStatus:()=>ct,Schema:()=>re,ZodAny:()=>Rr,ZodArray:()=>tr,ZodBigInt:()=>_o,ZodBoolean:()=>bo,ZodBranded:()=>Xi,ZodCatch:()=>Co,ZodDate:()=>xo,ZodDefault:()=>Ro,ZodDiscriminatedUnion:()=>au,ZodEffects:()=>nn,ZodEnum:()=>$o,ZodError:()=>Ct,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>uu,ZodIntersection:()=>wo,ZodIssueCode:()=>I,ZodLazy:()=>Eo,ZodLiteral:()=>To,ZodMap:()=>Cs,ZodNaN:()=>Is,ZodNativeEnum:()=>Po,ZodNever:()=>mn,ZodNull:()=>So,ZodNullable:()=>Nn,ZodNumber:()=>yo,ZodObject:()=>It,ZodOptional:()=>Ot,ZodParsedType:()=>z,ZodPipeline:()=>Yi,ZodPromise:()=>Cr,ZodReadonly:()=>Oo,ZodRecord:()=>cu,ZodSchema:()=>re,ZodSet:()=>Os,ZodString:()=>Pr,ZodSymbol:()=>Ps,ZodTransformer:()=>nn,ZodTuple:()=>An,ZodType:()=>re,ZodUndefined:()=>vo,ZodUnion:()=>ko,ZodUnknown:()=>er,ZodVoid:()=>Rs,addIssueToContext:()=>D,any:()=>MD,array:()=>zD,bigint:()=>CD,boolean:()=>wk,coerce:()=>cj,custom:()=>vk,date:()=>OD,datetimeRegex:()=>bk,defaultErrorMap:()=>Yn,discriminatedUnion:()=>FD,effect:()=>ej,enum:()=>XD,function:()=>KD,getErrorMap:()=>Es,getParsedType:()=>In,instanceof:()=>PD,intersection:()=>BD,isAborted:()=>su,isAsync:()=>Ts,isDirty:()=>iu,isValid:()=>$r,late:()=>$D,lazy:()=>GD,literal:()=>JD,makeIssue:()=>Ji,map:()=>VD,nan:()=>RD,nativeEnum:()=>YD,never:()=>jD,null:()=>ND,nullable:()=>nj,number:()=>kk,object:()=>Fm,objectUtil:()=>jm,oboolean:()=>aj,onumber:()=>ij,optional:()=>tj,ostring:()=>sj,pipeline:()=>oj,preprocess:()=>rj,promise:()=>QD,quotelessJson:()=>tD,record:()=>qD,set:()=>WD,setErrorMap:()=>rD,strictObject:()=>HD,string:()=>Sk,symbol:()=>ID,transformer:()=>ej,tuple:()=>ZD,undefined:()=>AD,union:()=>UD,unknown:()=>DD,util:()=>ce,void:()=>LD});var lu=x(()=>{ou();zm();mk();Gi();Ek();ru()});var Qi=x(()=>{lu()});function E(t,e,n){function r(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=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Bt(t){return t&&Object.assign(du,t),du}var dj,nr,du,As=x(()=>{dj=Object.freeze({status:"aborted"});nr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},du={}});var ue={};ye(ue,{BIGINT_FORMAT_RANGES:()=>$k,Class:()=>Zm,NUMBER_FORMAT_RANGES:()=>Xm,aborted:()=>Ao,allowsEval:()=>Km,assert:()=>gj,assertEqual:()=>pj,assertIs:()=>fj,assertNever:()=>hj,assertNotEqual:()=>mj,assignProp:()=>Wm,cached:()=>na,captureStackTrace:()=>mu,cleanEnum:()=>Rj,cleanRegex:()=>oa,clone:()=>Zt,createTransparentProxy:()=>Sj,defineLazy:()=>$e,esc:()=>Io,escapeRegex:()=>Or,extend:()=>Ej,finalizeIssue:()=>fn,floatSafeRemainder:()=>Vm,getElementAtPath:()=>yj,getEnumValues:()=>ta,getLengthableOrigin:()=>sa,getParsedType:()=>vj,getSizableOrigin:()=>Pk,isObject:()=>Ns,isPlainObject:()=>Ms,issue:()=>Ym,joinValues:()=>pu,jsonStringifyReplacer:()=>qm,merge:()=>Tj,normalizeParams:()=>J,nullish:()=>ra,numKeys:()=>xj,omit:()=>wj,optionalKeys:()=>Jm,partial:()=>$j,pick:()=>kj,prefixIssues:()=>Mn,primitiveTypes:()=>Tk,promiseAllObject:()=>_j,propertyKeyTypes:()=>Gm,randomString:()=>bj,required:()=>Pj,stringifyPrimitive:()=>fu,unwrapMessage:()=>ea});function pj(t){return t}function mj(t){return t}function fj(t){}function hj(t){throw new Error}function gj(t){}function ta(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function pu(t,e="|"){return t.map(n=>fu(n)).join(e)}function qm(t,e){return typeof e=="bigint"?e.toString():e}function na(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ra(t){return t==null}function oa(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Vm(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function $e(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Wm(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function yj(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function _j(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;se};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 Sj(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function fu(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Jm(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function kj(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return Zt(t,{...t._zod.def,shape:n,checks:[]})}function wj(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return Zt(t,{...t._zod.def,shape:n,checks:[]})}function Ej(t,e){if(!Ms(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return Wm(this,"shape",r),r},checks:[]};return Zt(t,n)}function Tj(t,e){return Zt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Wm(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function $j(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return Zt(e,{...e._zod.def,shape:o,checks:[]})}function Pj(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return Zt(e,{...e._zod.def,shape:o,checks:[]})}function Ao(t,e=0){for(let n=e;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function ea(t){return typeof t=="string"?t:t?.message}function fn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=ea(t.inst?._zod.def?.error?.(t))??ea(e?.error?.(t))??ea(n.customError?.(t))??ea(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Pk(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function sa(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ym(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function Rj(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var mu,Km,vj,Gm,Tk,Xm,$k,Zm,Dn=x(()=>{mu=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Km=na(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});vj=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}`)}},Gm=new Set(["string","number","symbol"]),Tk=new Set(["string","number","bigint","boolean","symbol","undefined"]);Xm={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]},$k={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Zm=class{constructor(...e){}}});function Qm(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function ef(t,e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;c{As();Dn();Rk=(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,qm,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},hu=E("$ZodError",Rk),ia=E("$ZodError",Rk,{Parent:Error})});var nf,rf,of,sf,af,No,cf,Mo,uf=x(()=>{As();tf();Dn();nf=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new nr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>fn(c,s,Bt())));throw mu(a,o?.callee),a}return i.value},rf=nf(ia),of=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>fn(c,s,Bt())));throw mu(a,o?.callee),a}return i.value},sf=of(ia),af=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new nr;return s.issues.length?{success:!1,error:new(t??hu)(s.issues.map(i=>fn(i,o,Bt())))}:{success:!0,data:s.value}},No=af(ia),cf=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>fn(i,o,Bt())))}:{success:!0,data:s.value}},Mo=cf(ia)});function zk(){return new RegExp(Oj,"u")}function Gk(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 Jk(t){return new RegExp(`^${Gk(t)}$`)}function Xk(t){let e=Gk({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Wk}T(?:${r})$`)}var Ck,Ok,Ik,Ak,Nk,Mk,Dk,jk,lf,Lk,Oj,Hk,Uk,Fk,Bk,Zk,df,qk,Vk,Wk,Kk,Yk,Qk,ew,tw,nw,rw,ow,yu=x(()=>{Ck=/^[cC][^\s-]{8,}$/,Ok=/^[0-9a-z]+$/,Ik=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ak=/^[0-9a-vA-V]{20}$/,Nk=/^[A-Za-z0-9]{27}$/,Mk=/^[a-zA-Z0-9_-]{21}$/,Dk=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jk=/^([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})$/,lf=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)$/,Lk=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Oj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Hk=/^(?:(?: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])$/,Uk=/^(([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})$/,Fk=/^((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])$/,Bk=/^(([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])$/,Zk=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,df=/^[A-Za-z0-9_-]*$/,qk=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Vk=/^\+(?:[0-9]){6,14}[0-9]$/,Wk="(?:(?:\\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])))",Kk=new RegExp(`^${Wk}$`);Yk=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Qk=/^\d+$/,ew=/^-?\d+(?:\.\d+)?/i,tw=/true|false/i,nw=/null/i,rw=/^[^A-Z]*$/,ow=/^[^a-z]*$/});var ut,sw,pf,mf,iw,aw,cw,uw,lw,aa,dw,pw,mw,fw,hw,gw,yw,_u=x(()=>{As();yu();Dn();ut=E("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),sw={number:"number",bigint:"bigint",object:"date"},pf=E("$ZodCheckLessThan",(t,e)=>{ut.init(t,e);let n=sw[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?r.value<=e.value:r.value{ut.init(t,e);let n=sw[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),iw=E("$ZodCheckMultipleOf",(t,e)=>{ut.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Vm(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),aw=E("$ZodCheckNumberFormat",(t,e)=>{ut.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Xm[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Qk)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,continue:!e.abort});return}}as&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),cw=E("$ZodCheckMaxLength",(t,e)=>{var n;ut.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ra(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let o=r.value;if(o.length<=e.maximum)return;let i=sa(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),uw=E("$ZodCheckMinLength",(t,e)=>{var n;ut.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ra(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=sa(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),lw=E("$ZodCheckLengthEquals",(t,e)=>{var n;ut.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ra(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=sa(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),aa=E("$ZodCheckStringFormat",(t,e)=>{var n,r;ut.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),dw=E("$ZodCheckRegex",(t,e)=>{aa.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),pw=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=rw),aa.init(t,e)}),mw=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ow),aa.init(t,e)}),fw=E("$ZodCheckIncludes",(t,e)=>{ut.init(t,e);let n=Or(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),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})}}),hw=E("$ZodCheckStartsWith",(t,e)=>{ut.init(t,e);let n=new RegExp(`^${Or(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),gw=E("$ZodCheckEndsWith",(t,e)=>{ut.init(t,e);let n=new RegExp(`.*${Or(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),yw=E("$ZodCheckOverwrite",(t,e)=>{ut.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var bu,ff=x(()=>{bu=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 r=e.split(` `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.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,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(` -`))}}});var tw,of=x(()=>{tw={major:4,minor:0,patch:0}});function hw(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function dj(t){if(!ef.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return hw(n)}function pj(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function nw(t,e,n){t.issues.length&&e.issues.push(...Dn(n,t.issues)),e.value[n]=t.value}function hu(t,e,n){t.issues.length&&e.issues.push(...Dn(n,t.issues)),e.value[n]=t.value}function rw(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Dn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function ow(t,e,n,r){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:n,errors:t.map(o=>o.issues.map(s=>hn(s,r,Ft())))}),e}function sf(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 n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=sf(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 n=[];for(let r=0;r{mu();Os();rf();Ym();pu();jn();of();jn();we=E("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=tw;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.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,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new nr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,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 nr;return a.then(c=>o(c,r,i))}return o(a,r,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}}),sa=E("$ZodString",(t,e)=>{we.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Nk(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Pe=E("$ZodStringFormat",(t,e)=>{oa.init(t,e),sa.init(t,e)}),af=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=bk),Pe.init(t,e)}),cf=E("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Qm(r))}else e.pattern??(e.pattern=Qm());Pe.init(t,e)}),uf=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=xk),Pe.init(t,e)}),lf=E("$ZodURL",(t,e)=>{Pe.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$k.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),df=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Sk()),Pe.init(t,e)}),pf=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=yk),Pe.init(t,e)}),mf=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=pk),Pe.init(t,e)}),ff=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=mk),Pe.init(t,e)}),hf=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=fk),Pe.init(t,e)}),gf=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=hk),Pe.init(t,e)}),yf=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=gk),Pe.init(t,e)}),dw=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ak(e)),Pe.init(t,e)}),pw=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ck),Pe.init(t,e)}),mw=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ik(e)),Pe.init(t,e)}),fw=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=_k),Pe.init(t,e)}),_f=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=vk),Pe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),bf=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=kk),Pe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),xf=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wk),Pe.init(t,e)}),Sf=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ek),Pe.init(t,e),t._zod.check=n=>{let[r,o]=n.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://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});vf=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Tk),Pe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{hw(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});kf=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=ef),Pe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{dj(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),wf=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Pk),Pe.init(t,e)});Ef=E("$ZodJWT",(t,e)=>{Pe.init(t,e),t._zod.check=n=>{pj(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),gu=E("$ZodNumber",(t,e)=>{we.init(t,e),t._zod.pattern=t._zod.bag.pattern??Dk,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),Tf=E("$ZodNumber",(t,e)=>{Bk.init(t,e),gu.init(t,e)}),$f=E("$ZodBoolean",(t,e)=>{we.init(t,e),t._zod.pattern=jk,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),Pf=E("$ZodNull",(t,e)=>{we.init(t,e),t._zod.pattern=Lk,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),Rf=E("$ZodUnknown",(t,e)=>{we.init(t,e),t._zod.parse=n=>n}),Cf=E("$ZodNever",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});Of=E("$ZodArray",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;inw(u,n,i))):nw(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});yu=E("$ZodObject",(t,e)=>{we.init(t,e);let n=Qi(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof we))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Hm(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});$e(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let h of m.values)p[f].add(h)}}return p});let r=d=>{let p=new fu(["shape","payload","ctx"]),f=n.value,m=_=>{let b=Co(_);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of f.keys)h[_]=`key_${g++}`;p.write("const newResult = {}");for(let _ of f.keys)if(f.optionalKeys.has(_)){let b=h[_];p.write(`const ${b} = ${m(_)};`);let S=Co(_);p.write(` +`))}}});var bw,hf=x(()=>{bw={major:4,minor:0,patch:0}});function Aw(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Ij(t){if(!df.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Aw(n)}function Aj(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function xw(t,e,n){t.issues.length&&e.issues.push(...Mn(n,t.issues)),e.value[n]=t.value}function xu(t,e,n){t.issues.length&&e.issues.push(...Mn(n,t.issues)),e.value[n]=t.value}function vw(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Mn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Sw(t,e,n,r){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:n,errors:t.map(o=>o.issues.map(s=>fn(s,r,Bt())))}),e}function gf(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 n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=gf(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 n=[];for(let r=0;r{_u();As();ff();uf();yu();Dn();hf();Dn();we=E("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=bw;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Ao(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,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new nr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Ao(s,d)))});else{if(s.issues.length===d)continue;c||(c=Ao(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 nr;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=No(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Mo(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ca=E("$ZodString",(t,e)=>{we.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Yk(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Pe=E("$ZodStringFormat",(t,e)=>{aa.init(t,e),ca.init(t,e)}),yf=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=jk),Pe.init(t,e)}),_f=E("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=lf(r))}else e.pattern??(e.pattern=lf());Pe.init(t,e)}),bf=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Lk),Pe.init(t,e)}),xf=E("$ZodURL",(t,e)=>{Pe.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:qk.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),vf=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=zk()),Pe.init(t,e)}),Sf=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Mk),Pe.init(t,e)}),kf=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ck),Pe.init(t,e)}),wf=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ok),Pe.init(t,e)}),Ef=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ik),Pe.init(t,e)}),Tf=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ak),Pe.init(t,e)}),$f=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Nk),Pe.init(t,e)}),Rw=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Xk(e)),Pe.init(t,e)}),Cw=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Kk),Pe.init(t,e)}),Ow=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Jk(e)),Pe.init(t,e)}),Iw=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Dk),Pe.init(t,e)}),Pf=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Hk),Pe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),Rf=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Uk),Pe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Cf=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Fk),Pe.init(t,e)}),Of=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Bk),Pe.init(t,e),t._zod.check=n=>{let[r,o]=n.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://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});If=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Zk),Pe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Aw(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});Af=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=df),Pe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Ij(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Nf=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Vk),Pe.init(t,e)});Mf=E("$ZodJWT",(t,e)=>{Pe.init(t,e),t._zod.check=n=>{Aj(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),vu=E("$ZodNumber",(t,e)=>{we.init(t,e),t._zod.pattern=t._zod.bag.pattern??ew,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),Df=E("$ZodNumber",(t,e)=>{aw.init(t,e),vu.init(t,e)}),jf=E("$ZodBoolean",(t,e)=>{we.init(t,e),t._zod.pattern=tw,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),Lf=E("$ZodNull",(t,e)=>{we.init(t,e),t._zod.pattern=nw,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),zf=E("$ZodUnknown",(t,e)=>{we.init(t,e),t._zod.parse=n=>n}),Hf=E("$ZodNever",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});Uf=E("$ZodArray",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;ixw(u,n,i))):xw(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});Su=E("$ZodObject",(t,e)=>{we.init(t,e);let n=na(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof we))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Jm(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});$e(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let h of m.values)p[f].add(h)}}return p});let r=d=>{let p=new bu(["shape","payload","ctx"]),f=n.value,m=_=>{let b=Io(_);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of f.keys)h[_]=`key_${g++}`;p.write("const newResult = {}");for(let _ of f.keys)if(f.optionalKeys.has(_)){let b=h[_];p.write(`const ${b} = ${m(_)};`);let v=Io(_);p.write(` if (${b}.issues.length) { - if (input[${S}] === undefined) { - if (${S} in input) { - newResult[${S}] = undefined; + if (input[${v}] === undefined) { + if (${v} in input) { + newResult[${v}] = undefined; } } else { payload.issues = payload.issues.concat( ${b}.issues.map((iss) => ({ ...iss, - path: iss.path ? [${S}, ...iss.path] : [${S}], + path: iss.path ? [${v}, ...iss.path] : [${v}], })) ); } } else if (${b}.value === undefined) { - if (${S} in input) newResult[${S}] = undefined; + if (${v} in input) newResult[${v}] = undefined; } else { - newResult[${S}] = ${b}.value; + newResult[${v}] = ${b}.value; } `)}else{let b=h[_];p.write(`const ${b} = ${m(_)};`),p.write(` if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({ ...iss, - path: iss.path ? [${Co(_)}, ...iss.path] : [${Co(_)}] - })));`),p.write(`newResult[${Co(_)}] = ${b}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,b)=>y(d,_,b)},o,s=Is,i=!iu.jitless,c=i&&Lm.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=n.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=r(e.shape)),d=o(d,p);else{d.value={};let b=l.shape;for(let S of l.keys){let T=b[S],M=T._zod.run({value:f[S],issues:[]},p),v=T._zod.optin==="optional"&&T._zod.optout==="optional";M instanceof Promise?m.push(M.then($=>v?rw($,d,S,f):hu($,d,S))):v?rw(M,d,S,f):hu(M,d,S)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(f)){if(g.has(b))continue;if(_==="never"){h.push(b);continue}let S=y.run({value:f[b],issues:[]},p);S instanceof Promise?m.push(S.then(T=>hu(T,d,b))):hu(S,d,b)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});_u=E("$ZodUnion",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),$e(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),$e(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),$e(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>ta(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);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=>ow(i,n,t,r)):ow(s,n,t,r)}}),If=E("$ZodDiscriminatedUnion",(t,e)=>{_u.init(t,e);let n=t._zod.parse;$e(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 r=Qi(()=>{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=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Af=E("$ZodIntersection",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>sw(n,c,u)):sw(n,s,i)}});Nf=E("$ZodRecord",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!As(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.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:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...Dn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Dn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>hn(u,r,Ft())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...Dn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...Dn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Mf=E("$ZodEnum",(t,e)=>{we.init(t,e);let n=Yi(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>zm.has(typeof r)).map(r=>typeof r=="string"?Or(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Df=E("$ZodLiteral",(t,e)=>{we.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Or(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),jf=E("$ZodTransform",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new nr;return n.value=o,n}}),Lf=E("$ZodOptional",(t,e)=>{we.init(t,e),t._zod.optin="optional",t._zod.optout="optional",$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ta(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),zf=E("$ZodNullable",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ta(n.source)}|null)$`):void 0}),$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Hf=E("$ZodDefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>iw(s,e)):iw(o,e)}});Uf=E("$ZodPrefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Ff=E("$ZodNonOptional",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>aw(s,t)):aw(o,t)}});Bf=E("$ZodCatch",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>hn(i,r,Ft()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>hn(s,r,Ft()))},input:n.value}),n.issues=[]),n)}}),Zf=E("$ZodPipe",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>e.in._zod.values),$e(t._zod,"optin",()=>e.in._zod.optin),$e(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>cw(s,e,r)):cw(o,e,r)}});qf=E("$ZodReadonly",(t,e)=>{we.init(t,e),$e(t._zod,"propValues",()=>e.innerType._zod.propValues),$e(t._zod,"values",()=>e.innerType._zod.values),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(uw):uw(o)}});Vf=E("$ZodCustom",(t,e)=>{ct.init(t,e),we.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>lw(s,n,r,t));lw(o,n,r,t)}})});function yw(){return{localeError:fj()}}var mj,fj,_w=x(()=>{jn();mj=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},fj=()=>{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(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${mj(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${uu(r.values[0])}`:`Invalid option: expected one of ${au(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;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 ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${au(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});var bu=x(()=>{});function bw(){return new ia}var ia,Ir,Kf=x(()=>{ia=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Ir=bw()});function Gf(t,e){return new t({type:"string",...J(e)})}function Jf(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function xu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function Xf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function Yf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function Qf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function eh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function th(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function nh(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function rh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function oh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function sh(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function ih(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function ah(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function ch(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function uh(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function lh(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function dh(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function ph(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function mh(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function fh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function hh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function gh(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function xw(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function Sw(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function vw(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function kw(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function yh(t,e){return new t({type:"number",checks:[],...J(e)})}function _h(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function bh(t,e){return new t({type:"boolean",...J(e)})}function xh(t,e){return new t({type:"null",...J(e)})}function Sh(t){return new t({type:"unknown"})}function vh(t,e){return new t({type:"never",...J(e)})}function Su(t,e){return new tf({check:"less_than",...J(e),value:t,inclusive:!1})}function aa(t,e){return new tf({check:"less_than",...J(e),value:t,inclusive:!0})}function vu(t,e){return new nf({check:"greater_than",...J(e),value:t,inclusive:!1})}function ca(t,e){return new nf({check:"greater_than",...J(e),value:t,inclusive:!0})}function ku(t,e){return new Fk({check:"multiple_of",...J(e),value:t})}function wu(t,e){return new Zk({check:"max_length",...J(e),maximum:t})}function Ns(t,e){return new qk({check:"min_length",...J(e),minimum:t})}function Eu(t,e){return new Vk({check:"length_equals",...J(e),length:t})}function kh(t,e){return new Wk({check:"string_format",format:"regex",...J(e),pattern:t})}function wh(t){return new Kk({check:"string_format",format:"lowercase",...J(t)})}function Eh(t){return new Gk({check:"string_format",format:"uppercase",...J(t)})}function Th(t,e){return new Jk({check:"string_format",format:"includes",...J(e),includes:t})}function $h(t,e){return new Xk({check:"string_format",format:"starts_with",...J(e),prefix:t})}function Ph(t,e){return new Yk({check:"string_format",format:"ends_with",...J(e),suffix:t})}function No(t){return new Qk({check:"overwrite",tx:t})}function Rh(t){return No(e=>e.normalize(t))}function Ch(){return No(t=>t.trim())}function Oh(){return No(t=>t.toLowerCase())}function Ih(){return No(t=>t.toUpperCase())}function ww(t,e,n){return new t({type:"array",element:e,...J(n)})}function Ah(t,e,n){let r=J(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Nh(t,e,n){return new t({type:"custom",check:"custom",fn:e,...J(n)})}var Ew=x(()=>{mu();jn()});var Tw=x(()=>{});function Mh(t,e){if(t instanceof ia){let r=new Tu(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.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]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new Tu(e);return n.process(t),n.emit(t,e)}function et(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.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 et(o.element,n);case"object":{for(let s in o.shape)if(et(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(et(s,n))return!0;return!1}case"intersection":return et(o.left,n)||et(o.right,n);case"tuple":{for(let s of o.items)if(et(s,n))return!0;return!!(o.rest&&et(o.rest,n))}case"record":return et(o.keyType,n)||et(o.valueType,n);case"map":return et(o.keyType,n)||et(o.valueType,n);case"set":return et(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return et(o.innerType,n);case"lazy":return et(o.getter(),n);case"default":return et(o.innerType,n);case"prefault":return et(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return et(o.in,n)||et(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Tu,$w=x(()=>{Kf();jn();Tu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ir,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,n={path:[],schemaPath:[]}){var r;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++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let m=f;m.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),y&&(m.format=s[y]??y,m.format===""&&delete m.format),b&&(m.contentEncoding=b),_&&_.size>0){let S=[..._];S.length===1?m.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{let m=f,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof S=="number"&&(m.exclusiveMinimum=S),typeof h=="number"&&(m.minimum=h,typeof S=="number"&&(S>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof b=="number"&&(m.exclusiveMaximum=b),typeof g=="number"&&(m.maximum=g,typeof b=="number"&&(b<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{let m=f;m.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 m=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let h=o.shape;for(let _ in h)m.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),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&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=f,h=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(h)?h.allOf:[h],...y(g)?g.allOf:[g]];m.allOf=_;break}case"tuple":{let m=f;m.type="array";let h=o.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.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 m=f,h=Yi(o.entries);h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=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];m.type=g===null?"null":typeof g,m.const=g}else h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),h.every(g=>typeof g=="boolean")&&(m.type="string"),h.every(g=>g===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(m,h)):m.anyOf=_.map(b=>({...h,contentMediaType:b})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,f.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 m=e._zod.innerType;this.process(m,d),a.ref=m;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"&&et(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.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(r.external){let h=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(h)return{ref:g(h)};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 f=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:f}=s(l);d.def={...d.schema},f&&(d.defId=f);let m=d.schema;for(let h in m)delete m[h];m.$ref=p};if(r.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/ + path: iss.path ? [${Io(_)}, ...iss.path] : [${Io(_)}] + })));`),p.write(`newResult[${Io(_)}] = ${b}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,b)=>y(d,_,b)},o,s=Ns,i=!du.jitless,c=i&&Km.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=n.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=r(e.shape)),d=o(d,p);else{d.value={};let b=l.shape;for(let v of l.keys){let T=b[v],M=T._zod.run({value:f[v],issues:[]},p),S=T._zod.optin==="optional"&&T._zod.optout==="optional";M instanceof Promise?m.push(M.then($=>S?vw($,d,v,f):xu($,d,v))):S?vw(M,d,v,f):xu(M,d,v)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(f)){if(g.has(b))continue;if(_==="never"){h.push(b);continue}let v=y.run({value:f[b],issues:[]},p);v instanceof Promise?m.push(v.then(T=>xu(T,d,b))):xu(v,d,b)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});ku=E("$ZodUnion",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),$e(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),$e(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),$e(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>oa(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);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=>Sw(i,n,t,r)):Sw(s,n,t,r)}}),Ff=E("$ZodDiscriminatedUnion",(t,e)=>{ku.init(t,e);let n=t._zod.parse;$e(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 r=na(()=>{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(!Ns(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Bf=E("$ZodIntersection",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>kw(n,c,u)):kw(n,s,i)}});Zf=E("$ZodRecord",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Ms(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.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:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...Mn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Mn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>fn(u,r,Bt())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...Mn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...Mn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),qf=E("$ZodEnum",(t,e)=>{we.init(t,e);let n=ta(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>Gm.has(typeof r)).map(r=>typeof r=="string"?Or(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Vf=E("$ZodLiteral",(t,e)=>{we.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Or(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),Wf=E("$ZodTransform",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new nr;return n.value=o,n}}),Kf=E("$ZodOptional",(t,e)=>{we.init(t,e),t._zod.optin="optional",t._zod.optout="optional",$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${oa(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),Gf=E("$ZodNullable",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${oa(n.source)}|null)$`):void 0}),$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Jf=E("$ZodDefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>ww(s,e)):ww(o,e)}});Xf=E("$ZodPrefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Yf=E("$ZodNonOptional",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Ew(s,t)):Ew(o,t)}});Qf=E("$ZodCatch",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>fn(i,r,Bt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>fn(s,r,Bt()))},input:n.value}),n.issues=[]),n)}}),eh=E("$ZodPipe",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>e.in._zod.values),$e(t._zod,"optin",()=>e.in._zod.optin),$e(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Tw(s,e,r)):Tw(o,e,r)}});th=E("$ZodReadonly",(t,e)=>{we.init(t,e),$e(t._zod,"propValues",()=>e.innerType._zod.propValues),$e(t._zod,"values",()=>e.innerType._zod.values),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then($w):$w(o)}});nh=E("$ZodCustom",(t,e)=>{ut.init(t,e),we.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>Pw(s,n,r,t));Pw(o,n,r,t)}})});function Mw(){return{localeError:Mj()}}var Nj,Mj,Dw=x(()=>{Dn();Nj=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},Mj=()=>{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(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${Nj(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${fu(r.values[0])}`:`Invalid option: expected one of ${pu(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;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 ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${pu(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});var wu=x(()=>{});function jw(){return new ua}var ua,Ir,oh=x(()=>{ua=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Ir=jw()});function sh(t,e){return new t({type:"string",...J(e)})}function ih(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function Eu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function ah(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function ch(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function uh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function lh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function dh(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function ph(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function mh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function fh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function hh(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function gh(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function yh(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function _h(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function bh(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function xh(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function vh(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function Sh(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function kh(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function wh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function Eh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function Th(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function Lw(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function zw(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function Hw(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function Uw(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function $h(t,e){return new t({type:"number",checks:[],...J(e)})}function Ph(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function Rh(t,e){return new t({type:"boolean",...J(e)})}function Ch(t,e){return new t({type:"null",...J(e)})}function Oh(t){return new t({type:"unknown"})}function Ih(t,e){return new t({type:"never",...J(e)})}function Tu(t,e){return new pf({check:"less_than",...J(e),value:t,inclusive:!1})}function la(t,e){return new pf({check:"less_than",...J(e),value:t,inclusive:!0})}function $u(t,e){return new mf({check:"greater_than",...J(e),value:t,inclusive:!1})}function da(t,e){return new mf({check:"greater_than",...J(e),value:t,inclusive:!0})}function Pu(t,e){return new iw({check:"multiple_of",...J(e),value:t})}function Ru(t,e){return new cw({check:"max_length",...J(e),maximum:t})}function Ds(t,e){return new uw({check:"min_length",...J(e),minimum:t})}function Cu(t,e){return new lw({check:"length_equals",...J(e),length:t})}function Ah(t,e){return new dw({check:"string_format",format:"regex",...J(e),pattern:t})}function Nh(t){return new pw({check:"string_format",format:"lowercase",...J(t)})}function Mh(t){return new mw({check:"string_format",format:"uppercase",...J(t)})}function Dh(t,e){return new fw({check:"string_format",format:"includes",...J(e),includes:t})}function jh(t,e){return new hw({check:"string_format",format:"starts_with",...J(e),prefix:t})}function Lh(t,e){return new gw({check:"string_format",format:"ends_with",...J(e),suffix:t})}function Do(t){return new yw({check:"overwrite",tx:t})}function zh(t){return Do(e=>e.normalize(t))}function Hh(){return Do(t=>t.trim())}function Uh(){return Do(t=>t.toLowerCase())}function Fh(){return Do(t=>t.toUpperCase())}function Fw(t,e,n){return new t({type:"array",element:e,...J(n)})}function Bh(t,e,n){let r=J(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Zh(t,e,n){return new t({type:"custom",check:"custom",fn:e,...J(n)})}var Bw=x(()=>{_u();Dn()});var Zw=x(()=>{});function qh(t,e){if(t instanceof ua){let r=new Ou(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.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]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new Ou(e);return n.process(t),n.emit(t,e)}function nt(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.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 nt(o.element,n);case"object":{for(let s in o.shape)if(nt(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(nt(s,n))return!0;return!1}case"intersection":return nt(o.left,n)||nt(o.right,n);case"tuple":{for(let s of o.items)if(nt(s,n))return!0;return!!(o.rest&&nt(o.rest,n))}case"record":return nt(o.keyType,n)||nt(o.valueType,n);case"map":return nt(o.keyType,n)||nt(o.valueType,n);case"set":return nt(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return nt(o.innerType,n);case"lazy":return nt(o.getter(),n);case"default":return nt(o.innerType,n);case"prefault":return nt(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return nt(o.in,n)||nt(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ou,qw=x(()=>{oh();Dn();Ou=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ir,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,n={path:[],schemaPath:[]}){var r;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++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let m=f;m.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),y&&(m.format=s[y]??y,m.format===""&&delete m.format),b&&(m.contentEncoding=b),_&&_.size>0){let v=[..._];v.length===1?m.pattern=v[0].source:v.length>1&&(a.schema.allOf=[...v.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{let m=f,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:v}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof v=="number"&&(m.exclusiveMinimum=v),typeof h=="number"&&(m.minimum=h,typeof v=="number"&&(v>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof b=="number"&&(m.exclusiveMaximum=b),typeof g=="number"&&(m.maximum=g,typeof b=="number"&&(b<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{let m=f;m.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 m=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let h=o.shape;for(let _ in h)m.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),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&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=f,h=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(h)?h.allOf:[h],...y(g)?g.allOf:[g]];m.allOf=_;break}case"tuple":{let m=f;m.type="array";let h=o.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.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 m=f,h=ta(o.entries);h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=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];m.type=g===null?"null":typeof g,m.const=g}else h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),h.every(g=>typeof g=="boolean")&&(m.type="string"),h.every(g=>g===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(m,h)):m.anyOf=_.map(b=>({...h,contentMediaType:b})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,f.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 m=e._zod.innerType;this.process(m,d),a.ref=m;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"&&nt(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.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(r.external){let h=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(h)return{ref:g(h)};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 f=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:f}=s(l);d.def={...d.schema},f&&(d.defId=f);let m=d.schema;for(let h in m)delete m[h];m.$ref=p};if(r.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/ -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(r.external){let f=r.external.registry.get(l[0])?.id;if(e!==l[0]&&f){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),f=p.def??p.schema,m={...f};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,m))}p.isParent||this.override({zodSchema:l,jsonSchema:f,path:p.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}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.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 Pw=x(()=>{});var kt=x(()=>{Os();Ym();qm();gw();mu();of();jn();pu();bu();Kf();rf();Tw();Ew();$w();Pw()});var Dh=x(()=>{kt()});function jh(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new Jj(n)}var Gj,Jj,Rw=x(()=>{kt();kt();Dh();Gj=E("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");we.init(t,e),t.def=e,t.parse=(n,r)=>Wm(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Io(t,n,r),t.parseAsync=async(n,r)=>Gm(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Ao(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Bt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))}),Jj=E("ZodMiniObject",(t,e)=>{yu.init(t,e),Gj.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var Cw=x(()=>{});var Ow=x(()=>{});var Iw=x(()=>{});var Aw=x(()=>{kt();Dh();Rw();Cw();kt();bu();Ow();Iw()});var Nw=x(()=>{Aw()});var Lh=x(()=>{Nw()});function rn(t){return!!t._zod}function Do(t){let e=Object.values(t);if(e.length===0)return jh({});let n=e.every(rn),r=e.every(o=>!rn(o));if(n)return jh(t);if(r)return Im(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ar(t,e){return rn(t)?Io(t,e):t.safeParse(e)}async function $u(t,e){return rn(t)?await Ao(t,e):await t.safeParseAsync(e)}function Nr(t){if(!t)return;let e;if(rn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ms(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Do(t)}}if(rn(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Pu(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 Dw(t){return t.description}function jw(t){if(rn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Ru(t){if(rn(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var ua=x(()=>{Ji();Lh()});var zh=x(()=>{kt()});var la={};_e(la,{ZodISODate:()=>zw,ZodISODateTime:()=>Lw,ZodISODuration:()=>Uw,ZodISOTime:()=>Hw,date:()=>Uh,datetime:()=>Hh,duration:()=>Bh,time:()=>Fh});function Hh(t){return xw(Lw,t)}function Uh(t){return Sw(zw,t)}function Fh(t){return vw(Hw,t)}function Bh(t){return kw(Uw,t)}var Lw,zw,Hw,Uw,Zh=x(()=>{kt();qh();Lw=E("ZodISODateTime",(t,e)=>{dw.init(t,e),Ne.init(t,e)});zw=E("ZodISODate",(t,e)=>{pw.init(t,e),Ne.init(t,e)});Hw=E("ZodISOTime",(t,e)=>{mw.init(t,e),Ne.init(t,e)});Uw=E("ZodISODuration",(t,e)=>{fw.init(t,e),Ne.init(t,e)})});var Fw,z5,da,Vh=x(()=>{kt();kt();Fw=(t,e)=>{lu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Zm(t,n)},flatten:{value:n=>Bm(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},z5=E("ZodError",Fw),da=E("ZodError",Fw,{Parent:Error})});var Bw,Zw,qw,Vw,Wh=x(()=>{kt();Vh();Bw=Vm(da),Zw=Km(da),qw=Jm(da),Vw=Xm(da)});function w(t){return Gf(i1,t)}function ye(t){return yh(Xw,t)}function Kw(t){return _h(w1,t)}function ot(t){return bh(E1,t)}function Yw(t){return xh(T1,t)}function Me(){return Sh($1)}function R1(t){return vh(P1,t)}function le(t,e){return ww(C1,t,e)}function U(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new Qw(n)}function wt(t,e){return new Qw({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:Me(),...ue.normalizeParams(e)})}function Oe(t,e){return new eE({type:"union",options:t,...ue.normalizeParams(e)})}function Jh(t,e,n){return new O1({type:"union",options:e,discriminator:t,...ue.normalizeParams(n)})}function Ou(t,e){return new I1({type:"intersection",left:t,right:e})}function Re(t,e,n){return new A1({type:"record",keyType:t,valueType:e,...ue.normalizeParams(n)})}function At(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Kh({type:"enum",entries:n,...ue.normalizeParams(e)})}function q(t,e){return new N1({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function tE(t){return new M1({type:"transform",transform:t})}function De(t){return new nE({type:"optional",innerType:t})}function Gw(t){return new D1({type:"nullable",innerType:t})}function L1(t,e){return new j1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function H1(t,e){return new z1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function U1(t,e){return new rE({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function B1(t,e){return new F1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Gh(t,e){return new Z1({type:"pipe",in:t,out:e})}function V1(t){return new q1({type:"readonly",innerType:t})}function W1(t){let e=new ct({check:"custom"});return e._zod.check=t,e}function sE(t,e){return Ah(oE,t??(()=>!0),e)}function K1(t,e={}){return Nh(oE,t,e)}function G1(t){let e=W1(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ue.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ue.issue(o))}},t(n.value,n)));return e}function Xh(t,e){return Gh(tE(t),e)}var Ue,Jw,i1,Ne,a1,Ww,Cu,c1,u1,l1,d1,p1,m1,f1,h1,g1,y1,_1,b1,x1,S1,v1,k1,Xw,w1,E1,T1,$1,P1,C1,Qw,eE,O1,I1,A1,Kh,N1,M1,nE,D1,j1,z1,rE,F1,Z1,q1,oE,qh=x(()=>{kt();kt();zh();Zh();Wh();Ue=E("ZodType",(t,e)=>(we.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Bt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>Bw(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>qw(t,n,r),t.parseAsync=async(n,r)=>Zw(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Vw(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(K1(n,r)),t.superRefine=n=>t.check(G1(n)),t.overwrite=n=>t.check(No(n)),t.optional=()=>De(t),t.nullable=()=>Gw(t),t.nullish=()=>De(Gw(t)),t.nonoptional=n=>U1(t,n),t.array=()=>le(t),t.or=n=>Oe([t,n]),t.and=n=>Ou(t,n),t.transform=n=>Gh(t,tE(n)),t.default=n=>L1(t,n),t.prefault=n=>H1(t,n),t.catch=n=>B1(t,n),t.pipe=n=>Gh(t,n),t.readonly=()=>V1(t),t.describe=n=>{let r=t.clone();return Ir.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Ir.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Ir.get(t);let r=t.clone();return Ir.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Jw=E("_ZodString",(t,e)=>{sa.init(t,e),Ue.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(kh(...r)),t.includes=(...r)=>t.check(Th(...r)),t.startsWith=(...r)=>t.check($h(...r)),t.endsWith=(...r)=>t.check(Ph(...r)),t.min=(...r)=>t.check(Ns(...r)),t.max=(...r)=>t.check(wu(...r)),t.length=(...r)=>t.check(Eu(...r)),t.nonempty=(...r)=>t.check(Ns(1,...r)),t.lowercase=r=>t.check(wh(r)),t.uppercase=r=>t.check(Eh(r)),t.trim=()=>t.check(Ch()),t.normalize=(...r)=>t.check(Rh(...r)),t.toLowerCase=()=>t.check(Oh()),t.toUpperCase=()=>t.check(Ih())}),i1=E("ZodString",(t,e)=>{sa.init(t,e),Jw.init(t,e),t.email=n=>t.check(Jf(a1,n)),t.url=n=>t.check(th(c1,n)),t.jwt=n=>t.check(gh(k1,n)),t.emoji=n=>t.check(nh(u1,n)),t.guid=n=>t.check(xu(Ww,n)),t.uuid=n=>t.check(Xf(Cu,n)),t.uuidv4=n=>t.check(Yf(Cu,n)),t.uuidv6=n=>t.check(Qf(Cu,n)),t.uuidv7=n=>t.check(eh(Cu,n)),t.nanoid=n=>t.check(rh(l1,n)),t.guid=n=>t.check(xu(Ww,n)),t.cuid=n=>t.check(oh(d1,n)),t.cuid2=n=>t.check(sh(p1,n)),t.ulid=n=>t.check(ih(m1,n)),t.base64=n=>t.check(mh(x1,n)),t.base64url=n=>t.check(fh(S1,n)),t.xid=n=>t.check(ah(f1,n)),t.ksuid=n=>t.check(ch(h1,n)),t.ipv4=n=>t.check(uh(g1,n)),t.ipv6=n=>t.check(lh(y1,n)),t.cidrv4=n=>t.check(dh(_1,n)),t.cidrv6=n=>t.check(ph(b1,n)),t.e164=n=>t.check(hh(v1,n)),t.datetime=n=>t.check(Hh(n)),t.date=n=>t.check(Uh(n)),t.time=n=>t.check(Fh(n)),t.duration=n=>t.check(Bh(n))});Ne=E("ZodStringFormat",(t,e)=>{Pe.init(t,e),Jw.init(t,e)}),a1=E("ZodEmail",(t,e)=>{uf.init(t,e),Ne.init(t,e)}),Ww=E("ZodGUID",(t,e)=>{af.init(t,e),Ne.init(t,e)}),Cu=E("ZodUUID",(t,e)=>{cf.init(t,e),Ne.init(t,e)}),c1=E("ZodURL",(t,e)=>{lf.init(t,e),Ne.init(t,e)}),u1=E("ZodEmoji",(t,e)=>{df.init(t,e),Ne.init(t,e)}),l1=E("ZodNanoID",(t,e)=>{pf.init(t,e),Ne.init(t,e)}),d1=E("ZodCUID",(t,e)=>{mf.init(t,e),Ne.init(t,e)}),p1=E("ZodCUID2",(t,e)=>{ff.init(t,e),Ne.init(t,e)}),m1=E("ZodULID",(t,e)=>{hf.init(t,e),Ne.init(t,e)}),f1=E("ZodXID",(t,e)=>{gf.init(t,e),Ne.init(t,e)}),h1=E("ZodKSUID",(t,e)=>{yf.init(t,e),Ne.init(t,e)}),g1=E("ZodIPv4",(t,e)=>{_f.init(t,e),Ne.init(t,e)}),y1=E("ZodIPv6",(t,e)=>{bf.init(t,e),Ne.init(t,e)}),_1=E("ZodCIDRv4",(t,e)=>{xf.init(t,e),Ne.init(t,e)}),b1=E("ZodCIDRv6",(t,e)=>{Sf.init(t,e),Ne.init(t,e)}),x1=E("ZodBase64",(t,e)=>{vf.init(t,e),Ne.init(t,e)}),S1=E("ZodBase64URL",(t,e)=>{kf.init(t,e),Ne.init(t,e)}),v1=E("ZodE164",(t,e)=>{wf.init(t,e),Ne.init(t,e)}),k1=E("ZodJWT",(t,e)=>{Ef.init(t,e),Ne.init(t,e)}),Xw=E("ZodNumber",(t,e)=>{gu.init(t,e),Ue.init(t,e),t.gt=(r,o)=>t.check(vu(r,o)),t.gte=(r,o)=>t.check(ca(r,o)),t.min=(r,o)=>t.check(ca(r,o)),t.lt=(r,o)=>t.check(Su(r,o)),t.lte=(r,o)=>t.check(aa(r,o)),t.max=(r,o)=>t.check(aa(r,o)),t.int=r=>t.check(Kw(r)),t.safe=r=>t.check(Kw(r)),t.positive=r=>t.check(vu(0,r)),t.nonnegative=r=>t.check(ca(0,r)),t.negative=r=>t.check(Su(0,r)),t.nonpositive=r=>t.check(aa(0,r)),t.multipleOf=(r,o)=>t.check(ku(r,o)),t.step=(r,o)=>t.check(ku(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});w1=E("ZodNumberFormat",(t,e)=>{Tf.init(t,e),Xw.init(t,e)});E1=E("ZodBoolean",(t,e)=>{$f.init(t,e),Ue.init(t,e)});T1=E("ZodNull",(t,e)=>{Pf.init(t,e),Ue.init(t,e)});$1=E("ZodUnknown",(t,e)=>{Rf.init(t,e),Ue.init(t,e)});P1=E("ZodNever",(t,e)=>{Cf.init(t,e),Ue.init(t,e)});C1=E("ZodArray",(t,e)=>{Of.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Ns(n,r)),t.nonempty=n=>t.check(Ns(1,n)),t.max=(n,r)=>t.check(wu(n,r)),t.length=(n,r)=>t.check(Eu(n,r)),t.unwrap=()=>t.element});Qw=E("ZodObject",(t,e)=>{yu.init(t,e),Ue.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Me()}),t.loose=()=>t.clone({...t._zod.def,catchall:Me()}),t.strict=()=>t.clone({...t._zod.def,catchall:R1()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ue.extend(t,n),t.merge=n=>ue.merge(t,n),t.pick=n=>ue.pick(t,n),t.omit=n=>ue.omit(t,n),t.partial=(...n)=>ue.partial(nE,t,n[0]),t.required=(...n)=>ue.required(rE,t,n[0])});eE=E("ZodUnion",(t,e)=>{_u.init(t,e),Ue.init(t,e),t.options=e.options});O1=E("ZodDiscriminatedUnion",(t,e)=>{eE.init(t,e),If.init(t,e)});I1=E("ZodIntersection",(t,e)=>{Af.init(t,e),Ue.init(t,e)});A1=E("ZodRecord",(t,e)=>{Nf.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Kh=E("ZodEnum",(t,e)=>{Mf.init(t,e),Ue.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Kh({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Kh({...e,checks:[],...ue.normalizeParams(o),entries:s})}});N1=E("ZodLiteral",(t,e)=>{Df.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]}})});M1=E("ZodTransform",(t,e)=>{jf.init(t,e),Ue.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ue.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ue.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});nE=E("ZodOptional",(t,e)=>{Lf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});D1=E("ZodNullable",(t,e)=>{zf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});j1=E("ZodDefault",(t,e)=>{Hf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});z1=E("ZodPrefault",(t,e)=>{Uf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});rE=E("ZodNonOptional",(t,e)=>{Ff.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});F1=E("ZodCatch",(t,e)=>{Bf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Z1=E("ZodPipe",(t,e)=>{Zf.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});q1=E("ZodReadonly",(t,e)=>{qf.init(t,e),Ue.init(t,e)});oE=E("ZodCustom",(t,e)=>{Vf.init(t,e),Ue.init(t,e)})});var iE=x(()=>{});var aE=x(()=>{});var cE=x(()=>{kt();qh();zh();Vh();Wh();iE();kt();_w();bu();Zh();aE();Ft(yw())});var uE=x(()=>{cE()});var lE=x(()=>{uE()});function $E(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function PE(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Qh,dE,Mr,Au,tt,pE,mE,t6,Y1,Q1,eg,Zt,pa,fE,ut,on,sn,lt,Nu,hE,tg,gE,yE,ng,ma,K,rg,_E,bE,n6,Mu,eL,Du,tL,fa,Ds,xE,nL,rL,oL,sL,iL,aL,og,cL,uL,sg,ju,lL,dL,Lu,pL,ha,ga,mL,ya,js,fL,_a,zu,Hu,Uu,r6,Fu,Bu,Zu,SE,vE,kE,ig,wE,ba,Ls,EE,hL,zs,gL,Hs,yL,ag,_L,qu,bL,xL,SL,vL,kL,wL,EL,TL,$L,PL,Us,RL,CL,Vu,cg,ug,lg,OL,IL,AL,dg,NL,ML,DL,jL,LL,TE,jo,zL,Wu,o6,HL,Fs,UL,s6,xa,FL,pg,BL,ZL,qL,VL,WL,KL,GL,Iu,JL,XL,YL,Sa,mg,QL,ez,tz,nz,rz,oz,sz,iz,az,cz,uz,lz,dz,pz,mz,fz,hz,gz,Bs,yz,_z,bz,Ku,xz,Sz,vz,fg,kz,i6,a6,c6,u6,l6,d6,Z,Yh,Lo=x(()=>{lE();Qh="2025-11-25",dE=[Qh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mr="io.modelcontextprotocol/related-task",Au="2.0",tt=sE(t=>t!==null&&(typeof t=="object"||typeof t=="function")),pE=Oe([w(),ye().int()]),mE=w(),t6=wt({ttl:ye().optional(),pollInterval:ye().optional()}),Y1=U({ttl:ye().optional()}),Q1=U({taskId:w()}),eg=wt({progressToken:pE.optional(),[Mr]:Q1.optional()}),Zt=U({_meta:eg.optional()}),pa=Zt.extend({task:Y1.optional()}),fE=t=>pa.safeParse(t).success,ut=U({method:w(),params:Zt.loose().optional()}),on=U({_meta:eg.optional()}),sn=U({method:w(),params:on.loose().optional()}),lt=wt({_meta:eg.optional()}),Nu=Oe([w(),ye().int()]),hE=U({jsonrpc:q(Au),id:Nu,...ut.shape}).strict(),tg=t=>hE.safeParse(t).success,gE=U({jsonrpc:q(Au),...sn.shape}).strict(),yE=t=>gE.safeParse(t).success,ng=U({jsonrpc:q(Au),id:Nu,result:lt}).strict(),ma=t=>ng.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"})(K||(K={}));rg=U({jsonrpc:q(Au),id:Nu.optional(),error:U({code:ye().int(),message:w(),data:Me().optional()})}).strict(),_E=t=>rg.safeParse(t).success,bE=Oe([hE,gE,ng,rg]),n6=Oe([ng,rg]),Mu=lt.strict(),eL=on.extend({requestId:Nu.optional(),reason:w().optional()}),Du=sn.extend({method:q("notifications/cancelled"),params:eL}),tL=U({src:w(),mimeType:w().optional(),sizes:le(w()).optional(),theme:At(["light","dark"]).optional()}),fa=U({icons:le(tL).optional()}),Ds=U({name:w(),title:w().optional()}),xE=Ds.extend({...Ds.shape,...fa.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),nL=Ou(U({applyDefaults:ot().optional()}),Re(w(),Me())),rL=Xh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ou(U({form:nL.optional(),url:tt.optional()}),Re(w(),Me()).optional())),oL=wt({list:tt.optional(),cancel:tt.optional(),requests:wt({sampling:wt({createMessage:tt.optional()}).optional(),elicitation:wt({create:tt.optional()}).optional()}).optional()}),sL=wt({list:tt.optional(),cancel:tt.optional(),requests:wt({tools:wt({call:tt.optional()}).optional()}).optional()}),iL=U({experimental:Re(w(),tt).optional(),sampling:U({context:tt.optional(),tools:tt.optional()}).optional(),elicitation:rL.optional(),roots:U({listChanged:ot().optional()}).optional(),tasks:oL.optional(),extensions:Re(w(),tt).optional()}),aL=Zt.extend({protocolVersion:w(),capabilities:iL,clientInfo:xE}),og=ut.extend({method:q("initialize"),params:aL}),cL=U({experimental:Re(w(),tt).optional(),logging:tt.optional(),completions:tt.optional(),prompts:U({listChanged:ot().optional()}).optional(),resources:U({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:U({listChanged:ot().optional()}).optional(),tasks:sL.optional(),extensions:Re(w(),tt).optional()}),uL=lt.extend({protocolVersion:w(),capabilities:cL,serverInfo:xE,instructions:w().optional()}),sg=sn.extend({method:q("notifications/initialized"),params:on.optional()}),ju=ut.extend({method:q("ping"),params:Zt.optional()}),lL=U({progress:ye(),total:De(ye()),message:De(w())}),dL=U({...on.shape,...lL.shape,progressToken:pE}),Lu=sn.extend({method:q("notifications/progress"),params:dL}),pL=Zt.extend({cursor:mE.optional()}),ha=ut.extend({params:pL.optional()}),ga=lt.extend({nextCursor:mE.optional()}),mL=At(["working","input_required","completed","failed","cancelled"]),ya=U({taskId:w(),status:mL,ttl:Oe([ye(),Yw()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:De(ye()),statusMessage:De(w())}),js=lt.extend({task:ya}),fL=on.merge(ya),_a=sn.extend({method:q("notifications/tasks/status"),params:fL}),zu=ut.extend({method:q("tasks/get"),params:Zt.extend({taskId:w()})}),Hu=lt.merge(ya),Uu=ut.extend({method:q("tasks/result"),params:Zt.extend({taskId:w()})}),r6=lt.loose(),Fu=ha.extend({method:q("tasks/list")}),Bu=ga.extend({tasks:le(ya)}),Zu=ut.extend({method:q("tasks/cancel"),params:Zt.extend({taskId:w()})}),SE=lt.merge(ya),vE=U({uri:w(),mimeType:De(w()),_meta:Re(w(),Me()).optional()}),kE=vE.extend({text:w()}),ig=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wE=vE.extend({blob:ig}),ba=At(["user","assistant"]),Ls=U({audience:le(ba).optional(),priority:ye().min(0).max(1).optional(),lastModified:la.datetime({offset:!0}).optional()}),EE=U({...Ds.shape,...fa.shape,uri:w(),description:De(w()),mimeType:De(w()),size:De(ye()),annotations:Ls.optional(),_meta:De(wt({}))}),hL=U({...Ds.shape,...fa.shape,uriTemplate:w(),description:De(w()),mimeType:De(w()),annotations:Ls.optional(),_meta:De(wt({}))}),zs=ha.extend({method:q("resources/list")}),gL=ga.extend({resources:le(EE)}),Hs=ha.extend({method:q("resources/templates/list")}),yL=ga.extend({resourceTemplates:le(hL)}),ag=Zt.extend({uri:w()}),_L=ag,qu=ut.extend({method:q("resources/read"),params:_L}),bL=lt.extend({contents:le(Oe([kE,wE]))}),xL=sn.extend({method:q("notifications/resources/list_changed"),params:on.optional()}),SL=ag,vL=ut.extend({method:q("resources/subscribe"),params:SL}),kL=ag,wL=ut.extend({method:q("resources/unsubscribe"),params:kL}),EL=on.extend({uri:w()}),TL=sn.extend({method:q("notifications/resources/updated"),params:EL}),$L=U({name:w(),description:De(w()),required:De(ot())}),PL=U({...Ds.shape,...fa.shape,description:De(w()),arguments:De(le($L)),_meta:De(wt({}))}),Us=ha.extend({method:q("prompts/list")}),RL=ga.extend({prompts:le(PL)}),CL=Zt.extend({name:w(),arguments:Re(w(),w()).optional()}),Vu=ut.extend({method:q("prompts/get"),params:CL}),cg=U({type:q("text"),text:w(),annotations:Ls.optional(),_meta:Re(w(),Me()).optional()}),ug=U({type:q("image"),data:ig,mimeType:w(),annotations:Ls.optional(),_meta:Re(w(),Me()).optional()}),lg=U({type:q("audio"),data:ig,mimeType:w(),annotations:Ls.optional(),_meta:Re(w(),Me()).optional()}),OL=U({type:q("tool_use"),name:w(),id:w(),input:Re(w(),Me()),_meta:Re(w(),Me()).optional()}),IL=U({type:q("resource"),resource:Oe([kE,wE]),annotations:Ls.optional(),_meta:Re(w(),Me()).optional()}),AL=EE.extend({type:q("resource_link")}),dg=Oe([cg,ug,lg,AL,IL]),NL=U({role:ba,content:dg}),ML=lt.extend({description:w().optional(),messages:le(NL)}),DL=sn.extend({method:q("notifications/prompts/list_changed"),params:on.optional()}),jL=U({title:w().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),LL=U({taskSupport:At(["required","optional","forbidden"]).optional()}),TE=U({...Ds.shape,...fa.shape,description:w().optional(),inputSchema:U({type:q("object"),properties:Re(w(),tt).optional(),required:le(w()).optional()}).catchall(Me()),outputSchema:U({type:q("object"),properties:Re(w(),tt).optional(),required:le(w()).optional()}).catchall(Me()).optional(),annotations:jL.optional(),execution:LL.optional(),_meta:Re(w(),Me()).optional()}),jo=ha.extend({method:q("tools/list")}),zL=ga.extend({tools:le(TE)}),Wu=lt.extend({content:le(dg).default([]),structuredContent:Re(w(),Me()).optional(),isError:ot().optional()}),o6=Wu.or(lt.extend({toolResult:Me()})),HL=pa.extend({name:w(),arguments:Re(w(),Me()).optional()}),Fs=ut.extend({method:q("tools/call"),params:HL}),UL=sn.extend({method:q("notifications/tools/list_changed"),params:on.optional()}),s6=U({autoRefresh:ot().default(!0),debounceMs:ye().int().nonnegative().default(300)}),xa=At(["debug","info","notice","warning","error","critical","alert","emergency"]),FL=Zt.extend({level:xa}),pg=ut.extend({method:q("logging/setLevel"),params:FL}),BL=on.extend({level:xa,logger:w().optional(),data:Me()}),ZL=sn.extend({method:q("notifications/message"),params:BL}),qL=U({name:w().optional()}),VL=U({hints:le(qL).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),WL=U({mode:At(["auto","required","none"]).optional()}),KL=U({type:q("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:le(dg).default([]),structuredContent:U({}).loose().optional(),isError:ot().optional(),_meta:Re(w(),Me()).optional()}),GL=Jh("type",[cg,ug,lg]),Iu=Jh("type",[cg,ug,lg,OL,KL]),JL=U({role:ba,content:Oe([Iu,le(Iu)]),_meta:Re(w(),Me()).optional()}),XL=pa.extend({messages:le(JL),modelPreferences:VL.optional(),systemPrompt:w().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le(w()).optional(),metadata:tt.optional(),tools:le(TE).optional(),toolChoice:WL.optional()}),YL=ut.extend({method:q("sampling/createMessage"),params:XL}),Sa=lt.extend({model:w(),stopReason:De(At(["endTurn","stopSequence","maxTokens"]).or(w())),role:ba,content:GL}),mg=lt.extend({model:w(),stopReason:De(At(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:ba,content:Oe([Iu,le(Iu)])}),QL=U({type:q("boolean"),title:w().optional(),description:w().optional(),default:ot().optional()}),ez=U({type:q("string"),title:w().optional(),description:w().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:At(["email","uri","date","date-time"]).optional(),default:w().optional()}),tz=U({type:At(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),nz=U({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),default:w().optional()}),rz=U({type:q("string"),title:w().optional(),description:w().optional(),oneOf:le(U({const:w(),title:w()})),default:w().optional()}),oz=U({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),enumNames:le(w()).optional(),default:w().optional()}),sz=Oe([nz,rz]),iz=U({type:q("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:U({type:q("string"),enum:le(w())}),default:le(w()).optional()}),az=U({type:q("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:U({anyOf:le(U({const:w(),title:w()}))}),default:le(w()).optional()}),cz=Oe([iz,az]),uz=Oe([oz,sz,cz]),lz=Oe([uz,QL,ez,tz]),dz=pa.extend({mode:q("form").optional(),message:w(),requestedSchema:U({type:q("object"),properties:Re(w(),lz),required:le(w()).optional()})}),pz=pa.extend({mode:q("url"),message:w(),elicitationId:w(),url:w().url()}),mz=Oe([dz,pz]),fz=ut.extend({method:q("elicitation/create"),params:mz}),hz=on.extend({elicitationId:w()}),gz=sn.extend({method:q("notifications/elicitation/complete"),params:hz}),Bs=lt.extend({action:At(["accept","decline","cancel"]),content:Xh(t=>t===null?void 0:t,Re(w(),Oe([w(),ye(),ot(),le(w())])).optional())}),yz=U({type:q("ref/resource"),uri:w()}),_z=U({type:q("ref/prompt"),name:w()}),bz=Zt.extend({ref:Oe([_z,yz]),argument:U({name:w(),value:w()}),context:U({arguments:Re(w(),w()).optional()}).optional()}),Ku=ut.extend({method:q("completion/complete"),params:bz});xz=lt.extend({completion:wt({values:le(w()).max(100),total:De(ye().int()),hasMore:De(ot())})}),Sz=U({uri:w().startsWith("file://"),name:w().optional(),_meta:Re(w(),Me()).optional()}),vz=ut.extend({method:q("roots/list"),params:Zt.optional()}),fg=lt.extend({roots:le(Sz)}),kz=sn.extend({method:q("notifications/roots/list_changed"),params:on.optional()}),i6=Oe([ju,og,Ku,pg,Vu,Us,zs,Hs,qu,vL,wL,Fs,jo,zu,Uu,Fu,Zu]),a6=Oe([Du,Lu,sg,kz,_a]),c6=Oe([Mu,Sa,mg,Bs,fg,Hu,Bu,js]),u6=Oe([ju,YL,fz,vz,zu,Uu,Fu,Zu]),l6=Oe([Du,Lu,ZL,TL,xL,UL,DL,_a,gz]),d6=Oe([Mu,uL,xz,ML,RL,gL,yL,bL,Wu,zL,Hu,Bu,js]),Z=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===K.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new Yh(o.elicitations,n)}return new t(e,n,r)}},Yh=class extends Z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Dr(t){return t==="completed"||t==="failed"||t==="cancelled"}var RE=x(()=>{});var OE,CE,IE,Gu=x(()=>{OE=Symbol("Let zodToJsonSchema decide on which parser to use"),CE={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"},IE=t=>typeof t=="string"?{...CE,name:t}:{...CE,...t}});var AE,hg=x(()=>{Gu();AE=t=>{let e=IE(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function gg(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function de(t,e,n,r,o){t[e]=n,gg(t,e,r,o)}var jr=x(()=>{});var Ju,Xu=x(()=>{Ju=(t,e)=>{let n=0;for(;n{Xu()});function NE(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==N.ZodAny&&(n.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(n,"minItems",t.exactLength.value,t.exactLength.message,e),de(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var yg=x(()=>{Ji();jr();Ge()});function ME(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var _g=x(()=>{jr()});function DE(){return{type:"boolean"}}var bg=x(()=>{});function Yu(t,e){return Y(t.type._def,e)}var Qu=x(()=>{Ge()});var jE,xg=x(()=>{Ge();jE=(t,e)=>Y(t.innerType._def,e)});function Sg(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Sg(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return wz(t,e)}}var wz,vg=x(()=>{jr();wz=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":de(n,"minimum",r.value,r.message,e);break;case"max":de(n,"maximum",r.value,r.message,e);break}return n}});function LE(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var kg=x(()=>{Ge()});function zE(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):je(e)}var wg=x(()=>{Ge();an()});function HE(t){return{type:"string",enum:Array.from(t.values)}}var Eg=x(()=>{});function UE(t,e){let n=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(Ez(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}var Ez,Tg=x(()=>{Ge();Ez=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function FE(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var $g=x(()=>{});function el(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":yn(n,"email",r.message,e);break;case"format:idn-email":yn(n,"idn-email",r.message,e);break;case"pattern:zod":Et(n,gn.email,r.message,e);break}break;case"url":yn(n,"uri",r.message,e);break;case"uuid":yn(n,"uuid",r.message,e);break;case"regex":Et(n,r.regex,r.message,e);break;case"cuid":Et(n,gn.cuid,r.message,e);break;case"cuid2":Et(n,gn.cuid2,r.message,e);break;case"startsWith":Et(n,RegExp(`^${Rg(r.value,e)}`),r.message,e);break;case"endsWith":Et(n,RegExp(`${Rg(r.value,e)}$`),r.message,e);break;case"datetime":yn(n,"date-time",r.message,e);break;case"date":yn(n,"date",r.message,e);break;case"time":yn(n,"time",r.message,e);break;case"duration":yn(n,"duration",r.message,e);break;case"length":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Et(n,RegExp(Rg(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&yn(n,"ipv4",r.message,e),r.version!=="v4"&&yn(n,"ipv6",r.message,e);break}case"base64url":Et(n,gn.base64url,r.message,e);break;case"jwt":Et(n,gn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Et(n,gn.ipv4Cidr,r.message,e),r.version!=="v4"&&Et(n,gn.ipv6Cidr,r.message,e);break}case"emoji":Et(n,gn.emoji(),r.message,e);break;case"ulid":{Et(n,gn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{yn(n,"binary",r.message,e);break}case"contentEncoding:base64":{de(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Et(n,gn.base64,r.message,e);break}}break}case"nanoid":Et(n,gn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Rg(t,e){return e.patternStrategy==="escape"?$z(t):t}function $z(t){let e="";for(let n=0;no.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):de(t,"format",e,n,r)}function Et(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:BE(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):de(t,"pattern",BE(e,r),n,r)}function BE(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c1&&r.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),f=p.def??p.schema,m={...f};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,m))}p.isParent||this.override({zodSchema:l,jsonSchema:f,path:p.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}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.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 Vw=x(()=>{});var kt=x(()=>{As();uf();tf();Nw();_u();hf();Dn();yu();wu();oh();ff();Zw();Bw();qw();Vw()});var Vh=x(()=>{kt()});function Wh(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new y1(n)}var g1,y1,Ww=x(()=>{kt();kt();Vh();g1=E("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");we.init(t,e),t.def=e,t.parse=(n,r)=>rf(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>No(t,n,r),t.parseAsync=async(n,r)=>sf(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Mo(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Zt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))}),y1=E("ZodMiniObject",(t,e)=>{Su.init(t,e),g1.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var Kw=x(()=>{});var Gw=x(()=>{});var Jw=x(()=>{});var Xw=x(()=>{kt();Vh();Ww();Kw();kt();wu();Gw();Jw()});var Yw=x(()=>{Xw()});var Kh=x(()=>{Yw()});function jn(t){return!!t._zod}function Lo(t){let e=Object.values(t);if(e.length===0)return Wh({});let n=e.every(jn),r=e.every(o=>!jn(o));if(n)return Wh(t);if(r)return Fm(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ar(t,e){return jn(t)?No(t,e):t.safeParse(e)}async function Iu(t,e){return jn(t)?await Mo(t,e):await t.safeParseAsync(e)}function Nr(t){if(!t)return;let e;if(jn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function js(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Lo(t)}}if(jn(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function x1(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function Au(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${x1(e.path)}`:e.message).join(` +`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function eE(t){return t.description}function tE(t){if(jn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Ls(t){if(jn(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var pa=x(()=>{Qi();Kh()});var Gh=x(()=>{kt()});var ma={};ye(ma,{ZodISODate:()=>rE,ZodISODateTime:()=>nE,ZodISODuration:()=>sE,ZodISOTime:()=>oE,date:()=>Xh,datetime:()=>Jh,duration:()=>Qh,time:()=>Yh});function Jh(t){return Lw(nE,t)}function Xh(t){return zw(rE,t)}function Yh(t){return Hw(oE,t)}function Qh(t){return Uw(sE,t)}var nE,rE,oE,sE,eg=x(()=>{kt();tg();nE=E("ZodISODateTime",(t,e)=>{Rw.init(t,e),Me.init(t,e)});rE=E("ZodISODate",(t,e)=>{Cw.init(t,e),Me.init(t,e)});oE=E("ZodISOTime",(t,e)=>{Ow.init(t,e),Me.init(t,e)});sE=E("ZodISODuration",(t,e)=>{Iw.init(t,e),Me.init(t,e)})});var iE,E6,fa,ng=x(()=>{kt();kt();iE=(t,e)=>{hu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ef(t,n)},flatten:{value:n=>Qm(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},E6=E("ZodError",iE),fa=E("ZodError",iE,{Parent:Error})});var aE,cE,uE,lE,rg=x(()=>{kt();ng();aE=nf(fa),cE=of(fa),uE=af(fa),lE=cf(fa)});function w(t){return sh(P1,t)}function be(t){return $h(hE,t)}function pE(t){return Ph(V1,t)}function it(t){return Rh(W1,t)}function gE(t){return Ch(K1,t)}function De(){return Oh(G1)}function X1(t){return Ih(J1,t)}function le(t,e){return Fw(Y1,t,e)}function U(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new yE(n)}function wt(t,e){return new yE({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ue.normalizeParams(e)})}function Oe(t,e){return new _E({type:"union",options:t,...ue.normalizeParams(e)})}function ig(t,e,n){return new Q1({type:"union",options:e,discriminator:t,...ue.normalizeParams(n)})}function Mu(t,e){return new eL({type:"intersection",left:t,right:e})}function Re(t,e,n){return new tL({type:"record",keyType:t,valueType:e,...ue.normalizeParams(n)})}function At(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new og({type:"enum",entries:n,...ue.normalizeParams(e)})}function q(t,e){return new nL({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function bE(t){return new rL({type:"transform",transform:t})}function je(t){return new xE({type:"optional",innerType:t})}function mE(t){return new oL({type:"nullable",innerType:t})}function iL(t,e){return new sL({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function cL(t,e){return new aL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function uL(t,e){return new vE({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function dL(t,e){return new lL({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function sg(t,e){return new pL({type:"pipe",in:t,out:e})}function fL(t){return new mL({type:"readonly",innerType:t})}function hL(t){let e=new ut({check:"custom"});return e._zod.check=t,e}function kE(t,e){return Bh(SE,t??(()=>!0),e)}function gL(t,e={}){return Zh(SE,t,e)}function yL(t){let e=hL(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ue.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ue.issue(o))}},t(n.value,n)));return e}function ag(t,e){return sg(bE(t),e)}var Ue,fE,P1,Me,R1,dE,Nu,C1,O1,I1,A1,N1,M1,D1,j1,L1,z1,H1,U1,F1,B1,Z1,q1,hE,V1,W1,K1,G1,J1,Y1,yE,_E,Q1,eL,tL,og,nL,rL,xE,oL,sL,aL,vE,lL,pL,mL,SE,tg=x(()=>{kt();kt();Gh();eg();rg();Ue=E("ZodType",(t,e)=>(we.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Zt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>aE(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>uE(t,n,r),t.parseAsync=async(n,r)=>cE(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>lE(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(gL(n,r)),t.superRefine=n=>t.check(yL(n)),t.overwrite=n=>t.check(Do(n)),t.optional=()=>je(t),t.nullable=()=>mE(t),t.nullish=()=>je(mE(t)),t.nonoptional=n=>uL(t,n),t.array=()=>le(t),t.or=n=>Oe([t,n]),t.and=n=>Mu(t,n),t.transform=n=>sg(t,bE(n)),t.default=n=>iL(t,n),t.prefault=n=>cL(t,n),t.catch=n=>dL(t,n),t.pipe=n=>sg(t,n),t.readonly=()=>fL(t),t.describe=n=>{let r=t.clone();return Ir.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Ir.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Ir.get(t);let r=t.clone();return Ir.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),fE=E("_ZodString",(t,e)=>{ca.init(t,e),Ue.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Ah(...r)),t.includes=(...r)=>t.check(Dh(...r)),t.startsWith=(...r)=>t.check(jh(...r)),t.endsWith=(...r)=>t.check(Lh(...r)),t.min=(...r)=>t.check(Ds(...r)),t.max=(...r)=>t.check(Ru(...r)),t.length=(...r)=>t.check(Cu(...r)),t.nonempty=(...r)=>t.check(Ds(1,...r)),t.lowercase=r=>t.check(Nh(r)),t.uppercase=r=>t.check(Mh(r)),t.trim=()=>t.check(Hh()),t.normalize=(...r)=>t.check(zh(...r)),t.toLowerCase=()=>t.check(Uh()),t.toUpperCase=()=>t.check(Fh())}),P1=E("ZodString",(t,e)=>{ca.init(t,e),fE.init(t,e),t.email=n=>t.check(ih(R1,n)),t.url=n=>t.check(dh(C1,n)),t.jwt=n=>t.check(Th(q1,n)),t.emoji=n=>t.check(ph(O1,n)),t.guid=n=>t.check(Eu(dE,n)),t.uuid=n=>t.check(ah(Nu,n)),t.uuidv4=n=>t.check(ch(Nu,n)),t.uuidv6=n=>t.check(uh(Nu,n)),t.uuidv7=n=>t.check(lh(Nu,n)),t.nanoid=n=>t.check(mh(I1,n)),t.guid=n=>t.check(Eu(dE,n)),t.cuid=n=>t.check(fh(A1,n)),t.cuid2=n=>t.check(hh(N1,n)),t.ulid=n=>t.check(gh(M1,n)),t.base64=n=>t.check(kh(F1,n)),t.base64url=n=>t.check(wh(B1,n)),t.xid=n=>t.check(yh(D1,n)),t.ksuid=n=>t.check(_h(j1,n)),t.ipv4=n=>t.check(bh(L1,n)),t.ipv6=n=>t.check(xh(z1,n)),t.cidrv4=n=>t.check(vh(H1,n)),t.cidrv6=n=>t.check(Sh(U1,n)),t.e164=n=>t.check(Eh(Z1,n)),t.datetime=n=>t.check(Jh(n)),t.date=n=>t.check(Xh(n)),t.time=n=>t.check(Yh(n)),t.duration=n=>t.check(Qh(n))});Me=E("ZodStringFormat",(t,e)=>{Pe.init(t,e),fE.init(t,e)}),R1=E("ZodEmail",(t,e)=>{bf.init(t,e),Me.init(t,e)}),dE=E("ZodGUID",(t,e)=>{yf.init(t,e),Me.init(t,e)}),Nu=E("ZodUUID",(t,e)=>{_f.init(t,e),Me.init(t,e)}),C1=E("ZodURL",(t,e)=>{xf.init(t,e),Me.init(t,e)}),O1=E("ZodEmoji",(t,e)=>{vf.init(t,e),Me.init(t,e)}),I1=E("ZodNanoID",(t,e)=>{Sf.init(t,e),Me.init(t,e)}),A1=E("ZodCUID",(t,e)=>{kf.init(t,e),Me.init(t,e)}),N1=E("ZodCUID2",(t,e)=>{wf.init(t,e),Me.init(t,e)}),M1=E("ZodULID",(t,e)=>{Ef.init(t,e),Me.init(t,e)}),D1=E("ZodXID",(t,e)=>{Tf.init(t,e),Me.init(t,e)}),j1=E("ZodKSUID",(t,e)=>{$f.init(t,e),Me.init(t,e)}),L1=E("ZodIPv4",(t,e)=>{Pf.init(t,e),Me.init(t,e)}),z1=E("ZodIPv6",(t,e)=>{Rf.init(t,e),Me.init(t,e)}),H1=E("ZodCIDRv4",(t,e)=>{Cf.init(t,e),Me.init(t,e)}),U1=E("ZodCIDRv6",(t,e)=>{Of.init(t,e),Me.init(t,e)}),F1=E("ZodBase64",(t,e)=>{If.init(t,e),Me.init(t,e)}),B1=E("ZodBase64URL",(t,e)=>{Af.init(t,e),Me.init(t,e)}),Z1=E("ZodE164",(t,e)=>{Nf.init(t,e),Me.init(t,e)}),q1=E("ZodJWT",(t,e)=>{Mf.init(t,e),Me.init(t,e)}),hE=E("ZodNumber",(t,e)=>{vu.init(t,e),Ue.init(t,e),t.gt=(r,o)=>t.check($u(r,o)),t.gte=(r,o)=>t.check(da(r,o)),t.min=(r,o)=>t.check(da(r,o)),t.lt=(r,o)=>t.check(Tu(r,o)),t.lte=(r,o)=>t.check(la(r,o)),t.max=(r,o)=>t.check(la(r,o)),t.int=r=>t.check(pE(r)),t.safe=r=>t.check(pE(r)),t.positive=r=>t.check($u(0,r)),t.nonnegative=r=>t.check(da(0,r)),t.negative=r=>t.check(Tu(0,r)),t.nonpositive=r=>t.check(la(0,r)),t.multipleOf=(r,o)=>t.check(Pu(r,o)),t.step=(r,o)=>t.check(Pu(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});V1=E("ZodNumberFormat",(t,e)=>{Df.init(t,e),hE.init(t,e)});W1=E("ZodBoolean",(t,e)=>{jf.init(t,e),Ue.init(t,e)});K1=E("ZodNull",(t,e)=>{Lf.init(t,e),Ue.init(t,e)});G1=E("ZodUnknown",(t,e)=>{zf.init(t,e),Ue.init(t,e)});J1=E("ZodNever",(t,e)=>{Hf.init(t,e),Ue.init(t,e)});Y1=E("ZodArray",(t,e)=>{Uf.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Ds(n,r)),t.nonempty=n=>t.check(Ds(1,n)),t.max=(n,r)=>t.check(Ru(n,r)),t.length=(n,r)=>t.check(Cu(n,r)),t.unwrap=()=>t.element});yE=E("ZodObject",(t,e)=>{Su.init(t,e),Ue.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),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:X1()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ue.extend(t,n),t.merge=n=>ue.merge(t,n),t.pick=n=>ue.pick(t,n),t.omit=n=>ue.omit(t,n),t.partial=(...n)=>ue.partial(xE,t,n[0]),t.required=(...n)=>ue.required(vE,t,n[0])});_E=E("ZodUnion",(t,e)=>{ku.init(t,e),Ue.init(t,e),t.options=e.options});Q1=E("ZodDiscriminatedUnion",(t,e)=>{_E.init(t,e),Ff.init(t,e)});eL=E("ZodIntersection",(t,e)=>{Bf.init(t,e),Ue.init(t,e)});tL=E("ZodRecord",(t,e)=>{Zf.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});og=E("ZodEnum",(t,e)=>{qf.init(t,e),Ue.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new og({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new og({...e,checks:[],...ue.normalizeParams(o),entries:s})}});nL=E("ZodLiteral",(t,e)=>{Vf.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]}})});rL=E("ZodTransform",(t,e)=>{Wf.init(t,e),Ue.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ue.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ue.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});xE=E("ZodOptional",(t,e)=>{Kf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});oL=E("ZodNullable",(t,e)=>{Gf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});sL=E("ZodDefault",(t,e)=>{Jf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});aL=E("ZodPrefault",(t,e)=>{Xf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});vE=E("ZodNonOptional",(t,e)=>{Yf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});lL=E("ZodCatch",(t,e)=>{Qf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});pL=E("ZodPipe",(t,e)=>{eh.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});mL=E("ZodReadonly",(t,e)=>{th.init(t,e),Ue.init(t,e)});SE=E("ZodCustom",(t,e)=>{nh.init(t,e),Ue.init(t,e)})});var wE=x(()=>{});var EE=x(()=>{});var TE=x(()=>{kt();tg();Gh();ng();rg();wE();kt();Dw();wu();eg();EE();Bt(Mw())});var $E=x(()=>{TE()});var PE=x(()=>{$E()});function qE(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function VE(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var ug,RE,Mr,ju,rt,CE,OE,U6,xL,vL,lg,qt,ha,IE,lt,rn,on,dt,Lu,AE,dg,NE,ME,pg,ga,K,mg,DE,jE,F6,zu,SL,Hu,kL,ya,zs,LE,wL,EL,TL,$L,PL,RL,fg,CL,OL,hg,Uu,IL,AL,Fu,NL,_a,ba,ML,xa,Hs,DL,va,Bu,Zu,qu,B6,Vu,Wu,Ku,zE,HE,UE,gg,FE,Sa,Us,BE,jL,Fs,LL,Bs,zL,yg,HL,Gu,UL,FL,BL,ZL,qL,VL,WL,KL,GL,JL,Zs,XL,YL,Ju,_g,bg,xg,QL,ez,tz,vg,nz,rz,oz,sz,iz,ZE,zo,az,Xu,Z6,cz,qs,uz,q6,ka,lz,Sg,dz,pz,mz,fz,hz,gz,yz,Du,_z,bz,xz,wa,kg,vz,Sz,kz,wz,Ez,Tz,$z,Pz,Rz,Cz,Oz,Iz,Az,Nz,Mz,Dz,jz,Lz,Vs,zz,Hz,Uz,Yu,Fz,Bz,Zz,wg,qz,V6,W6,K6,G6,J6,X6,Z,cg,Ho=x(()=>{PE();ug="2025-11-25",RE=[ug,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mr="io.modelcontextprotocol/related-task",ju="2.0",rt=kE(t=>t!==null&&(typeof t=="object"||typeof t=="function")),CE=Oe([w(),be().int()]),OE=w(),U6=wt({ttl:be().optional(),pollInterval:be().optional()}),xL=U({ttl:be().optional()}),vL=U({taskId:w()}),lg=wt({progressToken:CE.optional(),[Mr]:vL.optional()}),qt=U({_meta:lg.optional()}),ha=qt.extend({task:xL.optional()}),IE=t=>ha.safeParse(t).success,lt=U({method:w(),params:qt.loose().optional()}),rn=U({_meta:lg.optional()}),on=U({method:w(),params:rn.loose().optional()}),dt=wt({_meta:lg.optional()}),Lu=Oe([w(),be().int()]),AE=U({jsonrpc:q(ju),id:Lu,...lt.shape}).strict(),dg=t=>AE.safeParse(t).success,NE=U({jsonrpc:q(ju),...on.shape}).strict(),ME=t=>NE.safeParse(t).success,pg=U({jsonrpc:q(ju),id:Lu,result:dt}).strict(),ga=t=>pg.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"})(K||(K={}));mg=U({jsonrpc:q(ju),id:Lu.optional(),error:U({code:be().int(),message:w(),data:De().optional()})}).strict(),DE=t=>mg.safeParse(t).success,jE=Oe([AE,NE,pg,mg]),F6=Oe([pg,mg]),zu=dt.strict(),SL=rn.extend({requestId:Lu.optional(),reason:w().optional()}),Hu=on.extend({method:q("notifications/cancelled"),params:SL}),kL=U({src:w(),mimeType:w().optional(),sizes:le(w()).optional(),theme:At(["light","dark"]).optional()}),ya=U({icons:le(kL).optional()}),zs=U({name:w(),title:w().optional()}),LE=zs.extend({...zs.shape,...ya.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),wL=Mu(U({applyDefaults:it().optional()}),Re(w(),De())),EL=ag(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Mu(U({form:wL.optional(),url:rt.optional()}),Re(w(),De()).optional())),TL=wt({list:rt.optional(),cancel:rt.optional(),requests:wt({sampling:wt({createMessage:rt.optional()}).optional(),elicitation:wt({create:rt.optional()}).optional()}).optional()}),$L=wt({list:rt.optional(),cancel:rt.optional(),requests:wt({tools:wt({call:rt.optional()}).optional()}).optional()}),PL=U({experimental:Re(w(),rt).optional(),sampling:U({context:rt.optional(),tools:rt.optional()}).optional(),elicitation:EL.optional(),roots:U({listChanged:it().optional()}).optional(),tasks:TL.optional(),extensions:Re(w(),rt).optional()}),RL=qt.extend({protocolVersion:w(),capabilities:PL,clientInfo:LE}),fg=lt.extend({method:q("initialize"),params:RL}),CL=U({experimental:Re(w(),rt).optional(),logging:rt.optional(),completions:rt.optional(),prompts:U({listChanged:it().optional()}).optional(),resources:U({subscribe:it().optional(),listChanged:it().optional()}).optional(),tools:U({listChanged:it().optional()}).optional(),tasks:$L.optional(),extensions:Re(w(),rt).optional()}),OL=dt.extend({protocolVersion:w(),capabilities:CL,serverInfo:LE,instructions:w().optional()}),hg=on.extend({method:q("notifications/initialized"),params:rn.optional()}),Uu=lt.extend({method:q("ping"),params:qt.optional()}),IL=U({progress:be(),total:je(be()),message:je(w())}),AL=U({...rn.shape,...IL.shape,progressToken:CE}),Fu=on.extend({method:q("notifications/progress"),params:AL}),NL=qt.extend({cursor:OE.optional()}),_a=lt.extend({params:NL.optional()}),ba=dt.extend({nextCursor:OE.optional()}),ML=At(["working","input_required","completed","failed","cancelled"]),xa=U({taskId:w(),status:ML,ttl:Oe([be(),gE()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:je(be()),statusMessage:je(w())}),Hs=dt.extend({task:xa}),DL=rn.merge(xa),va=on.extend({method:q("notifications/tasks/status"),params:DL}),Bu=lt.extend({method:q("tasks/get"),params:qt.extend({taskId:w()})}),Zu=dt.merge(xa),qu=lt.extend({method:q("tasks/result"),params:qt.extend({taskId:w()})}),B6=dt.loose(),Vu=_a.extend({method:q("tasks/list")}),Wu=ba.extend({tasks:le(xa)}),Ku=lt.extend({method:q("tasks/cancel"),params:qt.extend({taskId:w()})}),zE=dt.merge(xa),HE=U({uri:w(),mimeType:je(w()),_meta:Re(w(),De()).optional()}),UE=HE.extend({text:w()}),gg=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),FE=HE.extend({blob:gg}),Sa=At(["user","assistant"]),Us=U({audience:le(Sa).optional(),priority:be().min(0).max(1).optional(),lastModified:ma.datetime({offset:!0}).optional()}),BE=U({...zs.shape,...ya.shape,uri:w(),description:je(w()),mimeType:je(w()),size:je(be()),annotations:Us.optional(),_meta:je(wt({}))}),jL=U({...zs.shape,...ya.shape,uriTemplate:w(),description:je(w()),mimeType:je(w()),annotations:Us.optional(),_meta:je(wt({}))}),Fs=_a.extend({method:q("resources/list")}),LL=ba.extend({resources:le(BE)}),Bs=_a.extend({method:q("resources/templates/list")}),zL=ba.extend({resourceTemplates:le(jL)}),yg=qt.extend({uri:w()}),HL=yg,Gu=lt.extend({method:q("resources/read"),params:HL}),UL=dt.extend({contents:le(Oe([UE,FE]))}),FL=on.extend({method:q("notifications/resources/list_changed"),params:rn.optional()}),BL=yg,ZL=lt.extend({method:q("resources/subscribe"),params:BL}),qL=yg,VL=lt.extend({method:q("resources/unsubscribe"),params:qL}),WL=rn.extend({uri:w()}),KL=on.extend({method:q("notifications/resources/updated"),params:WL}),GL=U({name:w(),description:je(w()),required:je(it())}),JL=U({...zs.shape,...ya.shape,description:je(w()),arguments:je(le(GL)),_meta:je(wt({}))}),Zs=_a.extend({method:q("prompts/list")}),XL=ba.extend({prompts:le(JL)}),YL=qt.extend({name:w(),arguments:Re(w(),w()).optional()}),Ju=lt.extend({method:q("prompts/get"),params:YL}),_g=U({type:q("text"),text:w(),annotations:Us.optional(),_meta:Re(w(),De()).optional()}),bg=U({type:q("image"),data:gg,mimeType:w(),annotations:Us.optional(),_meta:Re(w(),De()).optional()}),xg=U({type:q("audio"),data:gg,mimeType:w(),annotations:Us.optional(),_meta:Re(w(),De()).optional()}),QL=U({type:q("tool_use"),name:w(),id:w(),input:Re(w(),De()),_meta:Re(w(),De()).optional()}),ez=U({type:q("resource"),resource:Oe([UE,FE]),annotations:Us.optional(),_meta:Re(w(),De()).optional()}),tz=BE.extend({type:q("resource_link")}),vg=Oe([_g,bg,xg,tz,ez]),nz=U({role:Sa,content:vg}),rz=dt.extend({description:w().optional(),messages:le(nz)}),oz=on.extend({method:q("notifications/prompts/list_changed"),params:rn.optional()}),sz=U({title:w().optional(),readOnlyHint:it().optional(),destructiveHint:it().optional(),idempotentHint:it().optional(),openWorldHint:it().optional()}),iz=U({taskSupport:At(["required","optional","forbidden"]).optional()}),ZE=U({...zs.shape,...ya.shape,description:w().optional(),inputSchema:U({type:q("object"),properties:Re(w(),rt).optional(),required:le(w()).optional()}).catchall(De()),outputSchema:U({type:q("object"),properties:Re(w(),rt).optional(),required:le(w()).optional()}).catchall(De()).optional(),annotations:sz.optional(),execution:iz.optional(),_meta:Re(w(),De()).optional()}),zo=_a.extend({method:q("tools/list")}),az=ba.extend({tools:le(ZE)}),Xu=dt.extend({content:le(vg).default([]),structuredContent:Re(w(),De()).optional(),isError:it().optional()}),Z6=Xu.or(dt.extend({toolResult:De()})),cz=ha.extend({name:w(),arguments:Re(w(),De()).optional()}),qs=lt.extend({method:q("tools/call"),params:cz}),uz=on.extend({method:q("notifications/tools/list_changed"),params:rn.optional()}),q6=U({autoRefresh:it().default(!0),debounceMs:be().int().nonnegative().default(300)}),ka=At(["debug","info","notice","warning","error","critical","alert","emergency"]),lz=qt.extend({level:ka}),Sg=lt.extend({method:q("logging/setLevel"),params:lz}),dz=rn.extend({level:ka,logger:w().optional(),data:De()}),pz=on.extend({method:q("notifications/message"),params:dz}),mz=U({name:w().optional()}),fz=U({hints:le(mz).optional(),costPriority:be().min(0).max(1).optional(),speedPriority:be().min(0).max(1).optional(),intelligencePriority:be().min(0).max(1).optional()}),hz=U({mode:At(["auto","required","none"]).optional()}),gz=U({type:q("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:le(vg).default([]),structuredContent:U({}).loose().optional(),isError:it().optional(),_meta:Re(w(),De()).optional()}),yz=ig("type",[_g,bg,xg]),Du=ig("type",[_g,bg,xg,QL,gz]),_z=U({role:Sa,content:Oe([Du,le(Du)]),_meta:Re(w(),De()).optional()}),bz=ha.extend({messages:le(_z),modelPreferences:fz.optional(),systemPrompt:w().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:be().optional(),maxTokens:be().int(),stopSequences:le(w()).optional(),metadata:rt.optional(),tools:le(ZE).optional(),toolChoice:hz.optional()}),xz=lt.extend({method:q("sampling/createMessage"),params:bz}),wa=dt.extend({model:w(),stopReason:je(At(["endTurn","stopSequence","maxTokens"]).or(w())),role:Sa,content:yz}),kg=dt.extend({model:w(),stopReason:je(At(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:Sa,content:Oe([Du,le(Du)])}),vz=U({type:q("boolean"),title:w().optional(),description:w().optional(),default:it().optional()}),Sz=U({type:q("string"),title:w().optional(),description:w().optional(),minLength:be().optional(),maxLength:be().optional(),format:At(["email","uri","date","date-time"]).optional(),default:w().optional()}),kz=U({type:At(["number","integer"]),title:w().optional(),description:w().optional(),minimum:be().optional(),maximum:be().optional(),default:be().optional()}),wz=U({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),default:w().optional()}),Ez=U({type:q("string"),title:w().optional(),description:w().optional(),oneOf:le(U({const:w(),title:w()})),default:w().optional()}),Tz=U({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),enumNames:le(w()).optional(),default:w().optional()}),$z=Oe([wz,Ez]),Pz=U({type:q("array"),title:w().optional(),description:w().optional(),minItems:be().optional(),maxItems:be().optional(),items:U({type:q("string"),enum:le(w())}),default:le(w()).optional()}),Rz=U({type:q("array"),title:w().optional(),description:w().optional(),minItems:be().optional(),maxItems:be().optional(),items:U({anyOf:le(U({const:w(),title:w()}))}),default:le(w()).optional()}),Cz=Oe([Pz,Rz]),Oz=Oe([Tz,$z,Cz]),Iz=Oe([Oz,vz,Sz,kz]),Az=ha.extend({mode:q("form").optional(),message:w(),requestedSchema:U({type:q("object"),properties:Re(w(),Iz),required:le(w()).optional()})}),Nz=ha.extend({mode:q("url"),message:w(),elicitationId:w(),url:w().url()}),Mz=Oe([Az,Nz]),Dz=lt.extend({method:q("elicitation/create"),params:Mz}),jz=rn.extend({elicitationId:w()}),Lz=on.extend({method:q("notifications/elicitation/complete"),params:jz}),Vs=dt.extend({action:At(["accept","decline","cancel"]),content:ag(t=>t===null?void 0:t,Re(w(),Oe([w(),be(),it(),le(w())])).optional())}),zz=U({type:q("ref/resource"),uri:w()}),Hz=U({type:q("ref/prompt"),name:w()}),Uz=qt.extend({ref:Oe([Hz,zz]),argument:U({name:w(),value:w()}),context:U({arguments:Re(w(),w()).optional()}).optional()}),Yu=lt.extend({method:q("completion/complete"),params:Uz});Fz=dt.extend({completion:wt({values:le(w()).max(100),total:je(be().int()),hasMore:je(it())})}),Bz=U({uri:w().startsWith("file://"),name:w().optional(),_meta:Re(w(),De()).optional()}),Zz=lt.extend({method:q("roots/list"),params:qt.optional()}),wg=dt.extend({roots:le(Bz)}),qz=on.extend({method:q("notifications/roots/list_changed"),params:rn.optional()}),V6=Oe([Uu,fg,Yu,Sg,Ju,Zs,Fs,Bs,Gu,ZL,VL,qs,zo,Bu,qu,Vu,Ku]),W6=Oe([Hu,Fu,hg,qz,va]),K6=Oe([zu,wa,kg,Vs,wg,Zu,Wu,Hs]),G6=Oe([Uu,xz,Dz,Zz,Bu,qu,Vu,Ku]),J6=Oe([Hu,Fu,pz,KL,FL,uz,oz,va,Lz]),X6=Oe([zu,OL,Fz,rz,XL,LL,zL,UL,Xu,az,Zu,Wu,Hs]),Z=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===K.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new cg(o.elicitations,n)}return new t(e,n,r)}},cg=class extends Z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Dr(t){return t==="completed"||t==="failed"||t==="cancelled"}var WE=x(()=>{});var GE,KE,JE,Qu=x(()=>{GE=Symbol("Let zodToJsonSchema decide on which parser to use"),KE={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"},JE=t=>typeof t=="string"?{...KE,name:t}:{...KE,...t}});var XE,Eg=x(()=>{Qu();XE=t=>{let e=JE(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function Tg(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function de(t,e,n,r,o){t[e]=n,Tg(t,e,r,o)}var jr=x(()=>{});var el,tl=x(()=>{el=(t,e)=>{let n=0;for(;n{tl()});function YE(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==N.ZodAny&&(n.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(n,"minItems",t.exactLength.value,t.exactLength.message,e),de(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var $g=x(()=>{Qi();jr();Xe()});function QE(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var Pg=x(()=>{jr()});function eT(){return{type:"boolean"}}var Rg=x(()=>{});function nl(t,e){return Y(t.type._def,e)}var rl=x(()=>{Xe()});var tT,Cg=x(()=>{Xe();tT=(t,e)=>Y(t.innerType._def,e)});function Og(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Og(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Vz(t,e)}}var Vz,Ig=x(()=>{jr();Vz=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":de(n,"minimum",r.value,r.message,e);break;case"max":de(n,"maximum",r.value,r.message,e);break}return n}});function nT(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Ag=x(()=>{Xe()});function rT(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):Le(e)}var Ng=x(()=>{Xe();sn()});function oT(t){return{type:"string",enum:Array.from(t.values)}}var Mg=x(()=>{});function sT(t,e){let n=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(Wz(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}var Wz,Dg=x(()=>{Xe();Wz=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function iT(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var jg=x(()=>{});function ol(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":gn(n,"email",r.message,e);break;case"format:idn-email":gn(n,"idn-email",r.message,e);break;case"pattern:zod":Et(n,hn.email,r.message,e);break}break;case"url":gn(n,"uri",r.message,e);break;case"uuid":gn(n,"uuid",r.message,e);break;case"regex":Et(n,r.regex,r.message,e);break;case"cuid":Et(n,hn.cuid,r.message,e);break;case"cuid2":Et(n,hn.cuid2,r.message,e);break;case"startsWith":Et(n,RegExp(`^${zg(r.value,e)}`),r.message,e);break;case"endsWith":Et(n,RegExp(`${zg(r.value,e)}$`),r.message,e);break;case"datetime":gn(n,"date-time",r.message,e);break;case"date":gn(n,"date",r.message,e);break;case"time":gn(n,"time",r.message,e);break;case"duration":gn(n,"duration",r.message,e);break;case"length":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Et(n,RegExp(zg(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&gn(n,"ipv4",r.message,e),r.version!=="v4"&&gn(n,"ipv6",r.message,e);break}case"base64url":Et(n,hn.base64url,r.message,e);break;case"jwt":Et(n,hn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Et(n,hn.ipv4Cidr,r.message,e),r.version!=="v4"&&Et(n,hn.ipv6Cidr,r.message,e);break}case"emoji":Et(n,hn.emoji(),r.message,e);break;case"ulid":{Et(n,hn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{gn(n,"binary",r.message,e);break}case"contentEncoding:base64":{de(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Et(n,hn.base64,r.message,e);break}}break}case"nanoid":Et(n,hn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function zg(t,e){return e.patternStrategy==="escape"?Gz(t):t}function Gz(t){let e="";for(let n=0;no.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):de(t,"format",e,n,r)}function Et(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:aT(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):de(t,"pattern",aT(e,r),n,r)}function aT(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c{jr();gn={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:()=>(Pg===void 0&&(Pg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Pg),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-_]*$/};Tz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function nl(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===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=el(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===N.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===N.ZodBranded&&t.keyType._def.type._def.typeName===N.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=Yu(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var rl=x(()=>{Ji();Ge();tl();Qu();an()});function ZE(t,e){if(e.mapStrategy==="record")return nl(t,e);let n=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),r=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Cg=x(()=>{Ge();rl();an()});function qE(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var Og=x(()=>{});function VE(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var Ig=x(()=>{an()});function WE(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ag=x(()=>{});function GE(t,e){if(e.target==="openApi3")return KE(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in va&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=va[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.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(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return KE(t,e)}var va,KE,ol=x(()=>{Ge();va={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};KE=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>Y(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function JE(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:va[t.innerType._def.typeName],nullable:!0}:{type:[va[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Ng=x(()=>{Ge();ol()});function XE(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",gg(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var Mg=x(()=>{jr()});function YE(t,e){let n=e.target==="openAi",r={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=Rz(c);u&&n&&(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&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=Pz(t,e);return i!==void 0&&(r.additionalProperties=i),r}function Pz(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 Rz(t){try{return t.isOptional()}catch{return!0}}var Dg=x(()=>{Ge()});var QE,jg=x(()=>{Ge();an();QE=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:je(e)},n]}:je(e)}});var e0,Lg=x(()=>{Ge();e0=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let n=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}}});function t0(t,e){return Y(t.type._def,e)}var zg=x(()=>{Ge()});function n0(t,e){let r={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Hg=x(()=>{jr();Ge()});function r0(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Ug=x(()=>{Ge()});function o0(t){return{not:je(t)}}var Fg=x(()=>{an()});function s0(t){return je(t)}var Bg=x(()=>{an()});var i0,Zg=x(()=>{Ge();i0=(t,e)=>Y(t.innerType._def,e)});var a0,qg=x(()=>{Ji();an();yg();_g();bg();Qu();xg();vg();kg();wg();Eg();Tg();$g();Cg();Og();Ig();Ag();Ng();Mg();Dg();jg();Lg();zg();rl();Hg();tl();Ug();Fg();ol();Bg();Zg();a0=(t,e,n)=>{switch(e){case N.ZodString:return el(t,n);case N.ZodNumber:return XE(t,n);case N.ZodObject:return YE(t,n);case N.ZodBigInt:return ME(t,n);case N.ZodBoolean:return DE();case N.ZodDate:return Sg(t,n);case N.ZodUndefined:return o0(n);case N.ZodNull:return WE(n);case N.ZodArray:return NE(t,n);case N.ZodUnion:case N.ZodDiscriminatedUnion:return GE(t,n);case N.ZodIntersection:return UE(t,n);case N.ZodTuple:return r0(t,n);case N.ZodRecord:return nl(t,n);case N.ZodLiteral:return FE(t,n);case N.ZodEnum:return HE(t);case N.ZodNativeEnum:return qE(t);case N.ZodNullable:return JE(t,n);case N.ZodOptional:return QE(t,n);case N.ZodMap:return ZE(t,n);case N.ZodSet:return n0(t,n);case N.ZodLazy:return()=>t.getter()._def;case N.ZodPromise:return t0(t,n);case N.ZodNaN:case N.ZodNever:return VE(n);case N.ZodEffects:return zE(t,n);case N.ZodAny:return je(n);case N.ZodUnknown:return s0(n);case N.ZodDefault:return LE(t,n);case N.ZodBranded:return Yu(t,n);case N.ZodReadonly:return i0(t,n);case N.ZodCatch:return jE(t,n);case N.ZodPipeline:return e0(t,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(r=>{})(e)}}});function Y(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==OE)return a}if(r&&!n){let a=Cz(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=a0(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&Oz(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Cz,Oz,Ge=x(()=>{Gu();qg();Xu();an();Cz=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ju(e.currentPath,t.path)};case"none":case"seen":return t.path.lengthe.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},Oz=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var c0=x(()=>{});var Vg,Wg=x(()=>{Ge();hg();an();Vg=(t,e)=>{let n=AE(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??je(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??je(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 u0=x(()=>{Gu();hg();jr();Xu();Ge();c0();an();yg();_g();bg();Qu();xg();vg();kg();wg();Eg();Tg();$g();Cg();Og();Ig();Ag();Ng();Mg();Dg();jg();Lg();zg();Zg();rl();Hg();tl();Ug();Fg();ol();Bg();qg();Wg();Wg()});function Iz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Kg(t,e){return rn(t)?Mh(t,{target:Iz(e?.target),io:e?.pipeStrategy??"input"}):Vg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Gg(t){let n=Nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Ru(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Jg(t,e){let n=Ar(t,e);if(!n.success)throw n.error;return n.data}var Xg=x(()=>{Lh();ua();u0()});function l0(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function d0(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];l0(i)&&l0(s)?n[o]={...i,...s}:n[o]=s}return n}var Az,sl,p0=x(()=>{ua();Lo();RE();Xg();Az=6e4,sl=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(Du,n=>{this._oncancel(n)}),this.setNotificationHandler(Lu,n=>{this._onprogress(n)}),this.setRequestHandler(ju,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zu,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Uu,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.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,p=new Z(d.error.code,d.error.message,d.error.data);l(p)}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:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new Z(K.InvalidParams,`Task not found: ${s}`);if(!Dr(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(Dr(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Mr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Fu,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Z(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Zu,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,`Task not found: ${n.params.taskId}`);if(Dr(o.status))throw new Z(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new Z(K.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(K.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,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),ma(s)||_E(s)?this._onresponse(s):tg(s)?this._onrequest(s,i):yE(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 r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=Z.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Mr]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:K.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=fE(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,p)=>{if(i.signal.aborted)throw new Z(K.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(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:K.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:n,...r}=e.params,o=Number(n),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(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),ma(e))r(e);else{let i=new Z(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(ma(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,n))}}if(s||this._progressHandlers.delete(n),ma(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,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,js,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},Dr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new Z(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};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}r?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};r?.onprogress&&(this._progressHandlers.set(p,r.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Mr]:c}});let m=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let b=_ instanceof Z?_:new Z(K.RequestTimeout,String(_));l(b)};this._responseHandlers.set(p,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=Ar(n,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});let h=r?.timeout??Az,g=()=>m(Z.fromError(K.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let S=this._responseHandlers.get(p);S?S(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Hu,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Bu,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},SE,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Mr]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mr]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Mr]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Gg(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=Jg(e,o);return Promise.resolve(n(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,n){let r=Gg(e);this._notificationHandlers.set(r,o=>{let s=Jg(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){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,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&tg(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(K.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,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new Z(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new Z(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=_a.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Dr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new Z(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Dr(a.status))throw new Z(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=_a.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Dr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}}});var Ea=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 ka=class{};he._CodeOrName=ka;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var zo=class extends ka{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=zo;var cn=class extends ka{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof zo&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=cn;he.nil=new cn("");function m0(t,...e){let n=[t[0]],r=0;for(;r{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.ValueScope=Mt.ValueScopeName=Mt.Scope=Mt.varKinds=Mt.UsedValueState=void 0;var Nt=Ea(),ey=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},il;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(il||(Mt.UsedValueState=il={}));Mt.varKinds={const:new Nt.Name("const"),let:new Nt.Name("let"),var:new Nt.Name("var")};var al=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Nt.Name?e:this.name(e)}name(e){return new Nt.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};Mt.Scope=al;var cl=class extends Nt.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Nt._)`.${new Nt.Name(n)}[${r}]`}};Mt.ValueScopeName=cl;var Fz=(0,Nt._)`\n`,ty=class extends al{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Fz:Nt.nil}}get(){return this._scope}name(e){return new cl(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Nt._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=Nt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,il.Started);let l=n(u);if(l){let d=this.opts.es5?Mt.varKinds.var:Mt.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 ey(u);c.set(u,il.Completed)})}return s}};Mt.ValueScope=ty});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=Ea(),_n=ny(),Lr=Ea();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return Lr.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return Lr.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return Lr.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Lr.Name}});var pl=ny();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return pl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return pl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return pl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return pl.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 rr=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},ry=class extends rr{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?_n.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=qs(this.rhs,e,n)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},ul=class extends rr{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=qs(this.rhs,e,n),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return dl(e,this.rhs)}},oy=class extends ul{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},sy=class extends rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},iy=class extends rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ay=class extends rr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},cy=class extends rr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=qs(this.code,e,n),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},Ta=class extends rr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(Bz(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Fo(e,n.names),{})}},or=class extends Ta{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},uy=class extends Ta{},Zs=class extends or{};Zs.kind="else";var Ho=class t extends or{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Zs(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(h0(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=qs(this.condition,e,n),this}get names(){let e=super.names;return dl(e,this.condition),this.else&&Fo(e,this.else.names),e}};Ho.kind="if";var Uo=class extends or{};Uo.kind="for";var ly=class extends Uo{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=qs(this.iteration,e,n),this}get names(){return Fo(super.names,this.iteration.names)}},dy=class extends Uo{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?_n.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=dl(super.names,this.from);return dl(e,this.to)}},ll=class extends Uo{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=qs(this.iterable,e,n),this}get names(){return Fo(super.names,this.iterable.names)}},$a=class extends or{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};$a.kind="func";var Pa=class extends Ta{render(e){return"return "+super.render(e)}};Pa.kind="return";var py=class extends or{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Fo(e,this.catch.names),this.finally&&Fo(e,this.finally.names),e}},Ra=class extends or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ra.kind="catch";var Ca=class extends or{render(e){return"finally"+super.render(e)}};Ca.kind="finally";var my=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?` -`:""},this._extScope=e,this._scope=new _n.Scope({parent:e}),this._nodes=[new uy]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new ry(e,s,r)),s}const(e,n,r){return this._def(_n.varKinds.const,e,n,r)}let(e,n,r){return this._def(_n.varKinds.let,e,n,r)}var(e,n,r){return this._def(_n.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ul(e,n,r))}add(e,n){return this._leafNode(new oy(e,se.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new cy(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,pe.addCodeArg)(n,o));return n.push("}"),new pe._Code(n)}if(e,n,r){if(this._blockNode(new Ho(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ho(e))}else(){return this._elseNode(new Zs)}endIf(){return this._endBlockNode(Ho,Zs)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new ly(e),n)}forRange(e,n,r,o,s=this.opts.es5?_n.varKinds.var:_n.varKinds.let){let i=this._scope.toName(e);return this._for(new dy(s,i,n,r),()=>o(i))}forOf(e,n,r,o=_n.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof pe.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),r(s)})}return this._for(new ll("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?_n.varKinds.var:_n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new ll("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Uo)}label(e){return this._leafNode(new sy(e))}break(e){return this._leafNode(new iy(e))}return(e){let n=new Pa;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Pa)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new py;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new Ra(s),n(s)}return r&&(this._currNode=o.finally=new Ca,this.code(r)),this._endBlockNode(Ra,Ca)}throw(e){return this._leafNode(new ay(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=pe.nil,r,o){return this._blockNode(new $a(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode($a)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ho))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};se.CodeGen=my;function Fo(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function dl(t,e){return e instanceof pe._CodeOrName?Fo(t,e.names):t}function qs(t,e,n){if(t instanceof pe.Name)return r(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=r(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[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&&n[i.str]!==void 0)}}function Bz(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function h0(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${fy(t)}`}se.not=h0;var Zz=g0(se.operators.AND);function qz(...t){return t.reduce(Zz)}se.and=qz;var Vz=g0(se.operators.OR);function Wz(...t){return t.reduce(Vz)}se.or=Wz;function g0(t){return(e,n)=>e===pe.nil?n:n===pe.nil?e:(0,pe._)`${fy(e)} ${t} ${fy(n)}`}function fy(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 Te=oe(),Kz=Ea();function Gz(t){let e={};for(let n of t)e[n]=!0;return e}ae.toHash=Gz;function Jz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(b0(t,e),!x0(e,t.self.RULES.all))}ae.alwaysValidSchema=Jz;function b0(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||k0(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=b0;function x0(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ae.schemaHasRules=x0;function Xz(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ae.schemaHasRulesButRef=Xz;function Yz({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Te._)`${n}`}return(0,Te._)`${t}${e}${(0,Te.getProperty)(r)}`}ae.schemaRefOrVal=Yz;function Qz(t){return S0(decodeURIComponent(t))}ae.unescapeFragment=Qz;function eH(t){return encodeURIComponent(gy(t))}ae.escapeFragment=eH;function gy(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=gy;function S0(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=S0;function tH(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ae.eachItem=tH;function y0({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Te.Name?(s instanceof Te.Name?t(o,s,i):e(o,s,i),i):s instanceof Te.Name?(e(o,i,s),s):n(s,i);return a===Te.Name&&!(c instanceof Te.Name)?r(o,c):c}}ae.mergeEvaluated={props:y0({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,Te._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,Te._)`${n} || {}`).code((0,Te._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,Te._)`${n} || {}`),yy(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:v0}),items:y0({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,Te._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,Te._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function v0(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,Te._)`{}`);return e!==void 0&&yy(t,n,e),n}ae.evaluatedPropsToName=v0;function yy(t,e,n){Object.keys(n).forEach(r=>t.assign((0,Te._)`${e}${(0,Te.getProperty)(r)}`,!0))}ae.setEvaluated=yy;var _0={};function nH(t,e){return t.scopeValue("func",{ref:e,code:_0[e.code]||(_0[e.code]=new Kz._Code(e.code))})}ae.useFunc=nH;var hy;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(hy||(ae.Type=hy={}));function rH(t,e,n){if(t instanceof Te.Name){let r=e===hy.Num;return n?r?(0,Te._)`"[" + ${t} + "]"`:(0,Te._)`"['" + ${t} + "']"`:r?(0,Te._)`"/" + ${t}`:(0,Te._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Te.getProperty)(t).toString():"/"+gy(t)}ae.getErrorPath=rH;function k0(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=k0});var sr=L(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});var yt=oe(),oH={data:new yt.Name("data"),valCxt:new yt.Name("valCxt"),instancePath:new yt.Name("instancePath"),parentData:new yt.Name("parentData"),parentDataProperty:new yt.Name("parentDataProperty"),rootData:new yt.Name("rootData"),dynamicAnchors:new yt.Name("dynamicAnchors"),vErrors:new yt.Name("vErrors"),errors:new yt.Name("errors"),this:new yt.Name("this"),self:new yt.Name("self"),scope:new yt.Name("scope"),json:new yt.Name("json"),jsonPos:new yt.Name("jsonPos"),jsonLen:new yt.Name("jsonLen"),jsonPart:new yt.Name("jsonPart")};_y.default=oH});var Oa=L(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.extendErrors=_t.resetErrorsCount=_t.reportExtraError=_t.reportError=_t.keyword$DataError=_t.keywordError=void 0;var fe=oe(),ml=me(),Tt=sr();_t.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};_t.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 sH(t,e=_t.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=T0(t,e,n);r??(i||a)?w0(s,c):E0(o,(0,fe._)`[${c}]`)}_t.reportError=sH;function iH(t,e=_t.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=T0(t,e,n);w0(o,a),s||i||E0(r,Tt.default.vErrors)}_t.reportExtraError=iH;function aH(t,e){t.assign(Tt.default.errors,e),t.if((0,fe._)`${Tt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${Tt.default.vErrors}.length`,e),()=>t.assign(Tt.default.vErrors,null)))}_t.resetErrorsCount=aH;function cH({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Tt.default.errors,a=>{t.const(i,(0,fe._)`${Tt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(Tt.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`,n),t.assign((0,fe._)`${i}.data`,r))})}_t.extendErrors=cH;function w0(t,e){let n=t.const("err",e);t.if((0,fe._)`${Tt.default.vErrors} === null`,()=>t.assign(Tt.default.vErrors,(0,fe._)`[${n}]`),(0,fe._)`${Tt.default.vErrors}.push(${n})`),t.code((0,fe._)`${Tt.default.errors}++`)}function E0(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,fe._)`new ${t.ValidationError}(${e})`):(n.assign((0,fe._)`${r}.errors`,e),n.return(!1))}var Bo={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 T0(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,fe._)`{}`:uH(t,e,n)}function uH(t,e,n={}){let{gen:r,it:o}=t,s=[lH(o,n),dH(t,n)];return pH(t,e,s),r.object(...s)}function lH({errorPath:t},{instancePath:e}){let n=e?(0,fe.str)`${t}${(0,ml.getErrorPath)(e,ml.Type.Str)}`:t;return[Tt.default.instancePath,(0,fe.strConcat)(Tt.default.instancePath,n)]}function dH({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,fe.str)`${e}/${t}`;return n&&(o=(0,fe.str)`${o}${(0,ml.getErrorPath)(n,ml.Type.Str)}`),[Bo.schemaPath,o]}function pH(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([Bo.keyword,o],[Bo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&r.push([Bo.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Bo.schema,i],[Bo.parentSchema,(0,fe._)`${l}${d}`],[Tt.default.data,s]),u&&r.push([Bo.propertyName,u])}});var P0=L(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.boolOrEmptySchema=Vs.topBoolOrEmptySchema=void 0;var mH=Oa(),fH=oe(),hH=sr(),gH={message:"boolean schema is false"};function yH(t){let{gen:e,schema:n,validateName:r}=t;n===!1?$0(t,!1):typeof n=="object"&&n.$async===!0?e.return(hH.default.data):(e.assign((0,fH._)`${r}.errors`,null),e.return(!0))}Vs.topBoolOrEmptySchema=yH;function _H(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),$0(t)):n.var(e,!0)}Vs.boolOrEmptySchema=_H;function $0(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,mH.reportError)(o,gH,void 0,e)}});var by=L(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.getRules=Ws.isJSONType=void 0;var bH=["string","number","integer","boolean","null","object","array"],xH=new Set(bH);function SH(t){return typeof t=="string"&&xH.has(t)}Ws.isJSONType=SH;function vH(){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:{}}}Ws.getRules=vH});var xy=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function kH({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&R0(t,r)}zr.schemaHasRulesForType=kH;function R0(t,e){return e.rules.some(n=>C0(t,n))}zr.shouldUseGroup=R0;function C0(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}zr.shouldUseRule=C0});var Ia=L(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.reportTypeError=bt.checkDataTypes=bt.checkDataType=bt.coerceAndCheckDataType=bt.getJSONTypes=bt.getSchemaTypes=bt.DataType=void 0;var wH=by(),EH=xy(),TH=Oa(),ne=oe(),O0=me(),Ks;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ks||(bt.DataType=Ks={}));function $H(t){let e=I0(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}bt.getSchemaTypes=$H;function I0(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(wH.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}bt.getJSONTypes=I0;function PH(t,e){let{gen:n,data:r,opts:o}=t,s=RH(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,EH.schemaHasRulesForType)(t,e[0]));if(i){let a=vy(e,r,o.strictNumbers,Ks.Wrong);n.if(a,()=>{s.length?CH(t,e,s):ky(t)})}return i}bt.coerceAndCheckDataType=PH;var A0=new Set(["string","number","integer","boolean","null"]);function RH(t,e){return e?t.filter(n=>A0.has(n)||e==="array"&&n==="array"):[]}function CH(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(vy(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(let u of n)(A0.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),ky(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),OH(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null +]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[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 Lg,hn,Kz,sl=x(()=>{jr();hn={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:()=>(Lg===void 0&&(Lg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Lg),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-_]*$/};Kz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function il(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===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Le(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=ol(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===N.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===N.ZodBranded&&t.keyType._def.type._def.typeName===N.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=nl(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var al=x(()=>{Qi();Xe();sl();rl();sn()});function cT(t,e){if(e.mapStrategy==="record")return il(t,e);let n=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Le(e),r=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Le(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Hg=x(()=>{Xe();al();sn()});function uT(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var Ug=x(()=>{});function lT(t){return t.target==="openAi"?void 0:{not:Le({...t,currentPath:[...t.currentPath,"not"]})}}var Fg=x(()=>{sn()});function dT(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Bg=x(()=>{});function mT(t,e){if(e.target==="openApi3")return pT(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Ea&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Ea[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.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(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return pT(t,e)}var Ea,pT,cl=x(()=>{Xe();Ea={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};pT=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>Y(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function fT(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:Ea[t.innerType._def.typeName],nullable:!0}:{type:[Ea[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Zg=x(()=>{Xe();cl()});function hT(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",Tg(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var qg=x(()=>{jr()});function gT(t,e){let n=e.target==="openAi",r={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=Xz(c);u&&n&&(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&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=Jz(t,e);return i!==void 0&&(r.additionalProperties=i),r}function Jz(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 Xz(t){try{return t.isOptional()}catch{return!0}}var Vg=x(()=>{Xe()});var yT,Wg=x(()=>{Xe();sn();yT=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Le(e)},n]}:Le(e)}});var _T,Kg=x(()=>{Xe();_T=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let n=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}}});function bT(t,e){return Y(t.type._def,e)}var Gg=x(()=>{Xe()});function xT(t,e){let r={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Jg=x(()=>{jr();Xe()});function vT(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Xg=x(()=>{Xe()});function ST(t){return{not:Le(t)}}var Yg=x(()=>{sn()});function kT(t){return Le(t)}var Qg=x(()=>{sn()});var wT,ey=x(()=>{Xe();wT=(t,e)=>Y(t.innerType._def,e)});var ET,ty=x(()=>{Qi();sn();$g();Pg();Rg();rl();Cg();Ig();Ag();Ng();Mg();Dg();jg();Hg();Ug();Fg();Bg();Zg();qg();Vg();Wg();Kg();Gg();al();Jg();sl();Xg();Yg();cl();Qg();ey();ET=(t,e,n)=>{switch(e){case N.ZodString:return ol(t,n);case N.ZodNumber:return hT(t,n);case N.ZodObject:return gT(t,n);case N.ZodBigInt:return QE(t,n);case N.ZodBoolean:return eT();case N.ZodDate:return Og(t,n);case N.ZodUndefined:return ST(n);case N.ZodNull:return dT(n);case N.ZodArray:return YE(t,n);case N.ZodUnion:case N.ZodDiscriminatedUnion:return mT(t,n);case N.ZodIntersection:return sT(t,n);case N.ZodTuple:return vT(t,n);case N.ZodRecord:return il(t,n);case N.ZodLiteral:return iT(t,n);case N.ZodEnum:return oT(t);case N.ZodNativeEnum:return uT(t);case N.ZodNullable:return fT(t,n);case N.ZodOptional:return yT(t,n);case N.ZodMap:return cT(t,n);case N.ZodSet:return xT(t,n);case N.ZodLazy:return()=>t.getter()._def;case N.ZodPromise:return bT(t,n);case N.ZodNaN:case N.ZodNever:return lT(n);case N.ZodEffects:return rT(t,n);case N.ZodAny:return Le(n);case N.ZodUnknown:return kT(n);case N.ZodDefault:return nT(t,n);case N.ZodBranded:return nl(t,n);case N.ZodReadonly:return wT(t,n);case N.ZodCatch:return tT(t,n);case N.ZodPipeline:return _T(t,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(r=>{})(e)}}});function Y(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==GE)return a}if(r&&!n){let a=Yz(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=ET(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&Qz(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Yz,Qz,Xe=x(()=>{Qu();ty();tl();sn();Yz=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:el(e.currentPath,t.path)};case"none":case"seen":return t.path.lengthe.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Le(e)):e.$refStrategy==="seen"?Le(e):void 0}},Qz=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var TT=x(()=>{});var ny,ry=x(()=>{Xe();Eg();sn();ny=(t,e)=>{let n=XE(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??Le(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??Le(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 $T=x(()=>{Qu();Eg();jr();tl();Xe();TT();sn();$g();Pg();Rg();rl();Cg();Ig();Ag();Ng();Mg();Dg();jg();Hg();Ug();Fg();Bg();Zg();qg();Vg();Wg();Kg();Gg();ey();al();Jg();sl();Xg();Yg();cl();Qg();ty();ry();ry()});function eH(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function oy(t,e){return jn(t)?qh(t,{target:eH(e?.target),io:e?.pipeStrategy??"input"}):ny(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function sy(t){let n=Nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Ls(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function iy(t,e){let n=Ar(t,e);if(!n.success)throw n.error;return n.data}var ay=x(()=>{Kh();pa();$T()});function PT(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function RT(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];PT(i)&&PT(s)?n[o]={...i,...s}:n[o]=s}return n}var tH,ul,CT=x(()=>{pa();Ho();WE();ay();tH=6e4,ul=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(Hu,n=>{this._oncancel(n)}),this.setNotificationHandler(Fu,n=>{this._onprogress(n)}),this.setRequestHandler(Uu,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Bu,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(qu,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.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,p=new Z(d.error.code,d.error.message,d.error.data);l(p)}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:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new Z(K.InvalidParams,`Task not found: ${s}`);if(!Dr(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(Dr(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Mr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Vu,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Z(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ku,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,`Task not found: ${n.params.taskId}`);if(Dr(o.status))throw new Z(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new Z(K.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(K.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,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),ga(s)||DE(s)?this._onresponse(s):dg(s)?this._onrequest(s,i):ME(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 r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=Z.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Mr]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:K.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=IE(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,p)=>{if(i.signal.aborted)throw new Z(K.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(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:K.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:n,...r}=e.params,o=Number(n),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(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),ga(e))r(e);else{let i=new Z(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(ga(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,n))}}if(s||this._progressHandlers.delete(n),ga(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,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Hs,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},Dr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new Z(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};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}r?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};r?.onprogress&&(this._progressHandlers.set(p,r.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Mr]:c}});let m=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));let b=_ instanceof Z?_:new Z(K.RequestTimeout,String(_));l(b)};this._responseHandlers.set(p,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=Ar(n,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});let h=r?.timeout??tH,g=()=>m(Z.fromError(K.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let v=this._responseHandlers.get(p);v?v(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Zu,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Wu,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},zE,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Mr]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mr]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Mr]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=sy(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=iy(e,o);return Promise.resolve(n(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,n){let r=sy(e);this._notificationHandlers.set(r,o=>{let s=iy(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){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,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&dg(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(K.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,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new Z(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new Z(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=va.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Dr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new Z(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Dr(a.status))throw new Z(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=va.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Dr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}}});var Pa=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 Ta=class{};he._CodeOrName=Ta;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Uo=class extends Ta{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=Uo;var an=class extends Ta{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Uo&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=an;he.nil=new an("");function OT(t,...e){let n=[t[0]],r=0;for(;r{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.ValueScope=Mt.ValueScopeName=Mt.Scope=Mt.varKinds=Mt.UsedValueState=void 0;var Nt=Pa(),ly=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ll;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ll||(Mt.UsedValueState=ll={}));Mt.varKinds={const:new Nt.Name("const"),let:new Nt.Name("let"),var:new Nt.Name("var")};var dl=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Nt.Name?e:this.name(e)}name(e){return new Nt.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};Mt.Scope=dl;var pl=class extends Nt.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Nt._)`.${new Nt.Name(n)}[${r}]`}};Mt.ValueScopeName=pl;var lH=(0,Nt._)`\n`,dy=class extends dl{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?lH:Nt.nil}}get(){return this._scope}name(e){return new pl(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Nt._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=Nt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ll.Started);let l=n(u);if(l){let d=this.opts.es5?Mt.varKinds.var:Mt.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 ly(u);c.set(u,ll.Completed)})}return s}};Mt.ValueScope=dy});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=Pa(),yn=py(),Lr=Pa();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return Lr.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return Lr.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return Lr.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Lr.Name}});var gl=py();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return gl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return gl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return gl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return gl.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 rr=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},my=class extends rr{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?yn.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Ks(this.rhs,e,n)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},ml=class extends rr{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ks(this.rhs,e,n),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return hl(e,this.rhs)}},fy=class extends ml{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},hy=class extends rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},gy=class extends rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},yy=class extends rr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},_y=class extends rr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Ks(this.code,e,n),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},Ra=class extends rr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(dH(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Zo(e,n.names),{})}},or=class extends Ra{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},by=class extends Ra{},Ws=class extends or{};Ws.kind="else";var Fo=class t extends or{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Ws(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(AT(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Ks(this.condition,e,n),this}get names(){let e=super.names;return hl(e,this.condition),this.else&&Zo(e,this.else.names),e}};Fo.kind="if";var Bo=class extends or{};Bo.kind="for";var xy=class extends Bo{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Ks(this.iteration,e,n),this}get names(){return Zo(super.names,this.iteration.names)}},vy=class extends Bo{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?yn.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=hl(super.names,this.from);return hl(e,this.to)}},fl=class extends Bo{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Ks(this.iterable,e,n),this}get names(){return Zo(super.names,this.iterable.names)}},Ca=class extends or{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ca.kind="func";var Oa=class extends Ra{render(e){return"return "+super.render(e)}};Oa.kind="return";var Sy=class extends or{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Zo(e,this.catch.names),this.finally&&Zo(e,this.finally.names),e}},Ia=class extends or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ia.kind="catch";var Aa=class extends or{render(e){return"finally"+super.render(e)}};Aa.kind="finally";var ky=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?` +`:""},this._extScope=e,this._scope=new yn.Scope({parent:e}),this._nodes=[new by]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new my(e,s,r)),s}const(e,n,r){return this._def(yn.varKinds.const,e,n,r)}let(e,n,r){return this._def(yn.varKinds.let,e,n,r)}var(e,n,r){return this._def(yn.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ml(e,n,r))}add(e,n){return this._leafNode(new fy(e,se.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new _y(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,pe.addCodeArg)(n,o));return n.push("}"),new pe._Code(n)}if(e,n,r){if(this._blockNode(new Fo(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Fo(e))}else(){return this._elseNode(new Ws)}endIf(){return this._endBlockNode(Fo,Ws)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new xy(e),n)}forRange(e,n,r,o,s=this.opts.es5?yn.varKinds.var:yn.varKinds.let){let i=this._scope.toName(e);return this._for(new vy(s,i,n,r),()=>o(i))}forOf(e,n,r,o=yn.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof pe.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),r(s)})}return this._for(new fl("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?yn.varKinds.var:yn.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new fl("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Bo)}label(e){return this._leafNode(new hy(e))}break(e){return this._leafNode(new gy(e))}return(e){let n=new Oa;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Oa)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Sy;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new Ia(s),n(s)}return r&&(this._currNode=o.finally=new Aa,this.code(r)),this._endBlockNode(Ia,Aa)}throw(e){return this._leafNode(new yy(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=pe.nil,r,o){return this._blockNode(new Ca(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ca)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Fo))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};se.CodeGen=ky;function Zo(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function hl(t,e){return e instanceof pe._CodeOrName?Zo(t,e.names):t}function Ks(t,e,n){if(t instanceof pe.Name)return r(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=r(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[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&&n[i.str]!==void 0)}}function dH(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function AT(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${wy(t)}`}se.not=AT;var pH=NT(se.operators.AND);function mH(...t){return t.reduce(pH)}se.and=mH;var fH=NT(se.operators.OR);function hH(...t){return t.reduce(fH)}se.or=hH;function NT(t){return(e,n)=>e===pe.nil?n:n===pe.nil?e:(0,pe._)`${wy(e)} ${t} ${wy(n)}`}function wy(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 Te=oe(),gH=Pa();function yH(t){let e={};for(let n of t)e[n]=!0;return e}ae.toHash=yH;function _H(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(jT(t,e),!LT(e,t.self.RULES.all))}ae.alwaysValidSchema=_H;function jT(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||UT(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=jT;function LT(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ae.schemaHasRules=LT;function bH(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ae.schemaHasRulesButRef=bH;function xH({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Te._)`${n}`}return(0,Te._)`${t}${e}${(0,Te.getProperty)(r)}`}ae.schemaRefOrVal=xH;function vH(t){return zT(decodeURIComponent(t))}ae.unescapeFragment=vH;function SH(t){return encodeURIComponent(Ty(t))}ae.escapeFragment=SH;function Ty(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=Ty;function zT(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=zT;function kH(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ae.eachItem=kH;function MT({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Te.Name?(s instanceof Te.Name?t(o,s,i):e(o,s,i),i):s instanceof Te.Name?(e(o,i,s),s):n(s,i);return a===Te.Name&&!(c instanceof Te.Name)?r(o,c):c}}ae.mergeEvaluated={props:MT({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,Te._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,Te._)`${n} || {}`).code((0,Te._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,Te._)`${n} || {}`),$y(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:HT}),items:MT({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,Te._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,Te._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function HT(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,Te._)`{}`);return e!==void 0&&$y(t,n,e),n}ae.evaluatedPropsToName=HT;function $y(t,e,n){Object.keys(n).forEach(r=>t.assign((0,Te._)`${e}${(0,Te.getProperty)(r)}`,!0))}ae.setEvaluated=$y;var DT={};function wH(t,e){return t.scopeValue("func",{ref:e,code:DT[e.code]||(DT[e.code]=new gH._Code(e.code))})}ae.useFunc=wH;var Ey;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ey||(ae.Type=Ey={}));function EH(t,e,n){if(t instanceof Te.Name){let r=e===Ey.Num;return n?r?(0,Te._)`"[" + ${t} + "]"`:(0,Te._)`"['" + ${t} + "']"`:r?(0,Te._)`"/" + ${t}`:(0,Te._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Te.getProperty)(t).toString():"/"+Ty(t)}ae.getErrorPath=EH;function UT(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=UT});var sr=L(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var yt=oe(),TH={data:new yt.Name("data"),valCxt:new yt.Name("valCxt"),instancePath:new yt.Name("instancePath"),parentData:new yt.Name("parentData"),parentDataProperty:new yt.Name("parentDataProperty"),rootData:new yt.Name("rootData"),dynamicAnchors:new yt.Name("dynamicAnchors"),vErrors:new yt.Name("vErrors"),errors:new yt.Name("errors"),this:new yt.Name("this"),self:new yt.Name("self"),scope:new yt.Name("scope"),json:new yt.Name("json"),jsonPos:new yt.Name("jsonPos"),jsonLen:new yt.Name("jsonLen"),jsonPart:new yt.Name("jsonPart")};Py.default=TH});var Na=L(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.extendErrors=_t.resetErrorsCount=_t.reportExtraError=_t.reportError=_t.keyword$DataError=_t.keywordError=void 0;var fe=oe(),yl=me(),Tt=sr();_t.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};_t.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 $H(t,e=_t.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=ZT(t,e,n);r??(i||a)?FT(s,c):BT(o,(0,fe._)`[${c}]`)}_t.reportError=$H;function PH(t,e=_t.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=ZT(t,e,n);FT(o,a),s||i||BT(r,Tt.default.vErrors)}_t.reportExtraError=PH;function RH(t,e){t.assign(Tt.default.errors,e),t.if((0,fe._)`${Tt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${Tt.default.vErrors}.length`,e),()=>t.assign(Tt.default.vErrors,null)))}_t.resetErrorsCount=RH;function CH({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Tt.default.errors,a=>{t.const(i,(0,fe._)`${Tt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(Tt.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`,n),t.assign((0,fe._)`${i}.data`,r))})}_t.extendErrors=CH;function FT(t,e){let n=t.const("err",e);t.if((0,fe._)`${Tt.default.vErrors} === null`,()=>t.assign(Tt.default.vErrors,(0,fe._)`[${n}]`),(0,fe._)`${Tt.default.vErrors}.push(${n})`),t.code((0,fe._)`${Tt.default.errors}++`)}function BT(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,fe._)`new ${t.ValidationError}(${e})`):(n.assign((0,fe._)`${r}.errors`,e),n.return(!1))}var qo={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 ZT(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,fe._)`{}`:OH(t,e,n)}function OH(t,e,n={}){let{gen:r,it:o}=t,s=[IH(o,n),AH(t,n)];return NH(t,e,s),r.object(...s)}function IH({errorPath:t},{instancePath:e}){let n=e?(0,fe.str)`${t}${(0,yl.getErrorPath)(e,yl.Type.Str)}`:t;return[Tt.default.instancePath,(0,fe.strConcat)(Tt.default.instancePath,n)]}function AH({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,fe.str)`${e}/${t}`;return n&&(o=(0,fe.str)`${o}${(0,yl.getErrorPath)(n,yl.Type.Str)}`),[qo.schemaPath,o]}function NH(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([qo.keyword,o],[qo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&r.push([qo.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([qo.schema,i],[qo.parentSchema,(0,fe._)`${l}${d}`],[Tt.default.data,s]),u&&r.push([qo.propertyName,u])}});var VT=L(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.boolOrEmptySchema=Gs.topBoolOrEmptySchema=void 0;var MH=Na(),DH=oe(),jH=sr(),LH={message:"boolean schema is false"};function zH(t){let{gen:e,schema:n,validateName:r}=t;n===!1?qT(t,!1):typeof n=="object"&&n.$async===!0?e.return(jH.default.data):(e.assign((0,DH._)`${r}.errors`,null),e.return(!0))}Gs.topBoolOrEmptySchema=zH;function HH(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),qT(t)):n.var(e,!0)}Gs.boolOrEmptySchema=HH;function qT(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,MH.reportError)(o,LH,void 0,e)}});var Ry=L(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.getRules=Js.isJSONType=void 0;var UH=["string","number","integer","boolean","null","object","array"],FH=new Set(UH);function BH(t){return typeof t=="string"&&FH.has(t)}Js.isJSONType=BH;function ZH(){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:{}}}Js.getRules=ZH});var Cy=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function qH({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&WT(t,r)}zr.schemaHasRulesForType=qH;function WT(t,e){return e.rules.some(n=>KT(t,n))}zr.shouldUseGroup=WT;function KT(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}zr.shouldUseRule=KT});var Ma=L(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.reportTypeError=bt.checkDataTypes=bt.checkDataType=bt.coerceAndCheckDataType=bt.getJSONTypes=bt.getSchemaTypes=bt.DataType=void 0;var VH=Ry(),WH=Cy(),KH=Na(),ne=oe(),GT=me(),Xs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Xs||(bt.DataType=Xs={}));function GH(t){let e=JT(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}bt.getSchemaTypes=GH;function JT(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(VH.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}bt.getJSONTypes=JT;function JH(t,e){let{gen:n,data:r,opts:o}=t,s=XH(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,WH.schemaHasRulesForType)(t,e[0]));if(i){let a=Iy(e,r,o.strictNumbers,Xs.Wrong);n.if(a,()=>{s.length?YH(t,e,s):Ay(t)})}return i}bt.coerceAndCheckDataType=JH;var XT=new Set(["string","number","integer","boolean","null"]);function XH(t,e){return e?t.filter(n=>XT.has(n)||e==="array"&&n==="array"):[]}function YH(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(Iy(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(let u of n)(XT.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Ay(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),QH(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ne._)`+${o}`);return;case"integer":r.elseIf((0,ne._)`${i} === "boolean" || ${o} === null || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ne._)`+${o}`);return;case"boolean":r.elseIf((0,ne._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ne._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ne._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ne._)`${i} === "string" || ${i} === "number" - || ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function OH({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function Sy(t,e,n,r=Ks.Correct){let o=r===Ks.Correct?ne.operators.EQ:ne.operators.NEQ,s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===Ks.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}bt.checkDataType=Sy;function vy(t,e,n,r){if(t.length===1)return Sy(t[0],e,n,r);let o,s=(0,O0.toHash)(t);if(s.array&&s.object){let i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(let i in s)o=(0,ne.and)(o,Sy(i,e,n,r));return o}bt.checkDataTypes=vy;var IH={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function ky(t){let e=AH(t);(0,TH.reportError)(e,IH)}bt.reportTypeError=ky;function AH(t){let{gen:e,data:n,schema:r}=t,o=(0,O0.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var M0=L(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.assignDefaults=void 0;var Gs=oe(),NH=me();function MH(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)N0(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>N0(t,s,o.default))}fl.assignDefaults=MH;function N0(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Gs._)`${s}${(0,Gs.getProperty)(e)}`;if(o){(0,NH.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Gs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Gs._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Gs._)`${a} = ${(0,Gs.stringify)(n)}`)}});var un=L(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.validateUnion=Ee.validateArray=Ee.usePattern=Ee.callValidateCode=Ee.schemaProperties=Ee.allSchemaProperties=Ee.noPropertyInData=Ee.propertyInData=Ee.isOwnProperty=Ee.hasPropFunc=Ee.reportMissingProp=Ee.checkMissingProp=Ee.checkReportMissingProp=void 0;var Ie=oe(),wy=me(),Hr=sr(),DH=me();function jH(t,e){let{gen:n,data:r,it:o}=t;n.if(Ty(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ie._)`${e}`},!0),t.error()})}Ee.checkReportMissingProp=jH;function LH({gen:t,data:e,it:{opts:n}},r,o){return(0,Ie.or)(...r.map(s=>(0,Ie.and)(Ty(t,e,s,n.ownProperties),(0,Ie._)`${o} = ${s}`)))}Ee.checkMissingProp=LH;function zH(t,e){t.setParams({missingProperty:e},!0),t.error()}Ee.reportMissingProp=zH;function D0(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ie._)`Object.prototype.hasOwnProperty`})}Ee.hasPropFunc=D0;function Ey(t,e,n){return(0,Ie._)`${D0(t)}.call(${e}, ${n})`}Ee.isOwnProperty=Ey;function HH(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} !== undefined`;return r?(0,Ie._)`${o} && ${Ey(t,e,n)}`:o}Ee.propertyInData=HH;function Ty(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} === undefined`;return r?(0,Ie.or)(o,(0,Ie.not)(Ey(t,e,n))):o}Ee.noPropertyInData=Ty;function j0(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ee.allSchemaProperties=j0;function UH(t,e){return j0(e).filter(n=>!(0,wy.alwaysValidSchema)(t,e[n]))}Ee.schemaProperties=UH;function FH({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ie._)`${t}, ${e}, ${r}${o}`:e,d=[[Hr.default.instancePath,(0,Ie.strConcat)(Hr.default.instancePath,s)],[Hr.default.parentData,i.parentData],[Hr.default.parentDataProperty,i.parentDataProperty],[Hr.default.rootData,Hr.default.rootData]];i.opts.dynamicRef&&d.push([Hr.default.dynamicAnchors,Hr.default.dynamicAnchors]);let p=(0,Ie._)`${l}, ${n.object(...d)}`;return c!==Ie.nil?(0,Ie._)`${a}.call(${c}, ${p})`:(0,Ie._)`${a}(${p})`}Ee.callValidateCode=FH;var BH=(0,Ie._)`new RegExp`;function ZH({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ie._)`${o.code==="new RegExp"?BH:(0,DH.useFunc)(t,o)}(${n}, ${r})`})}Ee.usePattern=ZH;function qH(t){let{gen:e,data:n,keyword:r,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,Ie._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:wy.Type.Num},s),e.if((0,Ie.not)(s),a)})}}Ee.validateArray=qH;function VH(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,wy.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ie._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ie.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ee.validateUnion=VH});var H0=L(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.validateKeywordUsage=Ln.validSchemaType=Ln.funcKeywordCode=Ln.macroKeywordCode=void 0;var $t=oe(),Zo=sr(),WH=un(),KH=Oa();function GH(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=z0(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:$t.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ln.macroKeywordCode=GH;function JH(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;YH(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=z0(r,o,u),d=r.let("valid");t.block$data(d,p),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function p(){if(e.errors===!1)h(),e.modifying&&L0(t),g(()=>t.error());else{let y=e.async?f():m();e.modifying&&L0(t),g(()=>XH(t,y))}}function f(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,$t._)`await `),_=>r.assign(d,!1).if((0,$t._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,$t._)`${_}.errors`),()=>r.throw(_))),y}function m(){let y=(0,$t._)`${l}.errors`;return r.assign(y,null),h($t.nil),y}function h(y=e.async?(0,$t._)`await `:$t.nil){let _=c.opts.passContext?Zo.default.this:Zo.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,$t._)`${y}${(0,WH.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;r.if((0,$t.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}Ln.funcKeywordCode=JH;function L0(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,$t._)`${r.parentData}[${r.parentDataProperty}]`))}function XH(t,e){let{gen:n}=t;n.if((0,$t._)`Array.isArray(${e})`,()=>{n.assign(Zo.default.vErrors,(0,$t._)`${Zo.default.vErrors} === null ? ${e} : ${Zo.default.vErrors}.concat(${e})`).assign(Zo.default.errors,(0,$t._)`${Zo.default.vErrors}.length`),(0,KH.extendErrors)(t)},()=>t.error())}function YH({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function z0(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,$t.stringify)(n)})}function QH(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ln.validSchemaType=QH;function eU({schema:t,opts:e,self:n,errSchemaPath:r},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 "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Ln.validateKeywordUsage=eU});var F0=L(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.extendSubschemaMode=Ur.extendSubschemaData=Ur.getSubschema=void 0;var zn=oe(),U0=me();function tU(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}${(0,zn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,U0.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Ur.getSubschema=tU;function nU(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,zn._)`${e.data}${(0,zn.getProperty)(n)}`,!0);c(p),t.errorPath=(0,zn.str)`${u}${(0,U0.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,zn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof zn.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]}}Ur.extendSubschemaData=nU;function rU(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Ur.extendSubschemaMode=rU});var $y=L(($X,B0)=>{"use strict";B0.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var q0=L((PX,Z0)=>{"use strict";var Fr=Z0.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};hl(e,r,o,t,"",t)};Fr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Fr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Fr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Fr.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 hl(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in Fr.arrayKeywords)for(var p=0;p{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.getSchemaRefs=Dt.resolveUrl=Dt.normalizeId=Dt._getFullPath=Dt.getFullPath=Dt.inlineRef=void 0;var sU=me(),iU=$y(),aU=q0(),cU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function uU(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Py(t):e?V0(t)<=e:!1}Dt.inlineRef=uU;var lU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Py(t){for(let e in t){if(lU.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Py)||typeof n=="object"&&Py(n))return!0}return!1}function V0(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!cU.has(n)&&(typeof t[n]=="object"&&(0,sU.eachItem)(t[n],r=>e+=V0(r)),e===1/0))return 1/0}return e}function W0(t,e="",n){n!==!1&&(e=Js(e));let r=t.parse(e);return K0(t,r)}Dt.getFullPath=W0;function K0(t,e){return t.serialize(e).split("#")[0]+"#"}Dt._getFullPath=K0;var dU=/#\/?$/;function Js(t){return t?t.replace(dU,""):""}Dt.normalizeId=Js;function pU(t,e,n){return n=Js(n),t.resolve(e,n)}Dt.resolveUrl=pU;var mU=/^[a-z_][-a-z0-9._]*$/i;function fU(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Js(t[n]||e),s={"":o},i=W0(r,o,!1),a={},c=new Set;return aU(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,g=s[m];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(b){let S=this.opts.uriResolver.resolve;if(b=Js(g?S(g,b):b),c.has(b))throw l(b);c.add(b);let T=this.refs[b];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?u(d,T.schema,b):b!==Js(h)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!mU.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,p,f){if(p!==void 0&&!iU(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Dt.getSchemaRefs=fU});var Da=L(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var Q0=P0(),G0=Ia(),Cy=xy(),gl=Ia(),hU=M0(),Ma=H0(),Ry=F0(),V=oe(),ee=sr(),gU=Aa(),ir=me(),Na=Oa();function yU(t){if(nT(t)&&(rT(t),tT(t))){xU(t);return}eT(t,()=>(0,Q0.topBoolOrEmptySchema)(t))}Br.validateFunctionCode=yU;function eT({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,r.$async,()=>{t.code((0,V._)`"use strict"; ${J0(n,o)}`),bU(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${_U(o)}`,r.$async,()=>t.code(J0(n,o)).code(s))}function _U(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 bU(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 xU(t){let{schema:e,opts:n,gen:r}=t;eT(t,()=>{n.$comment&&e.$comment&&sT(t),EU(t),r.let(ee.default.vErrors,null),r.let(ee.default.errors,0),n.unevaluated&&SU(t),oT(t),PU(t)})}function SU(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,V._)`${n}.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 J0(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${n} */`:V.nil}function vU(t,e){if(nT(t)&&(rT(t),tT(t))){kU(t,e);return}(0,Q0.boolOrEmptySchema)(t,e)}function tT({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function nT(t){return typeof t.schema!="boolean"}function kU(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&sT(t),TU(t),$U(t);let s=r.const("_errs",ee.default.errors);oT(t,s),r.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function rT(t){(0,ir.checkUnknownRules)(t),wU(t)}function oT(t,e){if(t.opts.jtd)return X0(t,[],!1,e);let n=(0,G0.getSchemaTypes)(t.schema),r=(0,G0.coerceAndCheckDataType)(t,n);X0(t,n,!r,e)}function wU(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function EU(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ir.checkStrictMode)(t,"default is ignored in the schema root")}function TU(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,gU.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function $U(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function sT({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$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)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function PU(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$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._)`${r}.errors`,ee.default.vErrors),s.unevaluated&&RU(t),e.return((0,V._)`${ee.default.errors} === 0`))}function RU({gen:t,evaluated:e,props:n,items:r}){n instanceof V.Name&&t.assign((0,V._)`${e}.props`,n),r instanceof V.Name&&t.assign((0,V._)`${e}.items`,r)}function X0(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ir.schemaHasRulesButRef)(s,l))){o.block(()=>aT(t,"$ref",l.all.$ref.definition));return}c.jtd||CU(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Cy.shouldUseGroup)(s,p)&&(p.type?(o.if((0,gl.checkDataType)(p.type,i,c.strictNumbers)),Y0(t,p),e.length===1&&e[0]===p.type&&n&&(o.else(),(0,gl.reportTypeError)(t)),o.endIf()):Y0(t,p),a||o.if((0,V._)`${ee.default.errors} === ${r||0}`))}}function Y0(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,hU.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,Cy.shouldUseRule)(r,s)&&aT(t,s.keyword,s.definition,e.type)})}function CU(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(OU(t,e),t.opts.allowUnionTypes||IU(t,e),AU(t,t.dataTypes))}function OU(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{iT(t.dataTypes,n)||Oy(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),MU(t,e)}}function IU(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Oy(t,"use allowUnionTypes to allow union type keyword")}function AU(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Cy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>NU(e,i))&&Oy(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function NU(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function iT(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function MU(t,e){let n=[];for(let r of t.dataTypes)iT(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Oy(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ir.checkStrictMode)(t,e,t.opts.strictTypes)}var yl=class{constructor(e,n,r){if((0,Ma.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ir.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",cT(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ma.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,n,r){this.failResult((0,V.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,V.not)(e),void 0,n)}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:n}=this;this.fail((0,V._)`${n} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?Na.reportExtraError:Na.reportError)(this,this.def.error,n)}$dataError(){(0,Na.reportError)(this,this.def.$dataError||Na.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Na.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=V.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=V.nil,n=V.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,V.or)((0,V._)`${o} === undefined`,n)),e!==V.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(r.length){if(!(n instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,V._)`${(0,gl.checkDataTypes)(c,n,s.opts.strictNumbers,gl.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${n})`}return V.nil}}subschema(e,n){let r=(0,Ry.getSubschema)(this.it,e);(0,Ry.extendSubschemaData)(r,this.it,e),(0,Ry.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return vU(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ir.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ir.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,V.Name)),!0}};Br.KeywordCxt=yl;function aT(t,e,n,r){let o=new yl(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Ma.funcKeywordCode)(o,n):"macro"in n?(0,Ma.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Ma.funcKeywordCode)(o,n)}var DU=/^\/(?:[^~]|~0|~1)*$/,jU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cT(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!DU.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=jU.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 r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[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,ir.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Br.getData=cT});var _l=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 ja=L(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Ny=Aa(),My=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Ny.resolveUrl)(e,n,r),this.missingSchema=(0,Ny.normalizeId)((0,Ny.getFullPath)(e,this.missingRef))}};Dy.default=My});var xl=L(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.resolveSchema=ln.getCompilingSchema=ln.resolveRef=ln.compileSchema=ln.SchemaEnv=void 0;var bn=oe(),LU=_l(),qo=sr(),xn=Aa(),uT=me(),zU=Da(),Xs=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,xn.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};ln.SchemaEnv=Xs;function Ly(t){let e=lT.call(this,t);if(e)return e;let n=(0,xn.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new bn.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:LU.default,code:(0,bn._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:qo.default.data,parentData:qo.default.parentData,parentDataProperty:qo.default.parentDataProperty,dataNames:[qo.default.data],dataPathArr:[bn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,bn.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:bn.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,bn._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,zU.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(qo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${qo.default.self}`,`${qo.default.scope}`,l)(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:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:h}=u;f.evaluated={props:m instanceof bn.Name?void 0:m,items:h instanceof bn.Name?void 0:h,dynamicProps:m instanceof bn.Name,dynamicItems:h instanceof bn.Name},f.source&&(f.source.evaluated=(0,bn.stringify)(f.evaluated))}return t.validate=f,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)}}ln.compileSchema=Ly;function HU(t,e,n){var r;n=(0,xn.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=BU.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Xs({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=UU.call(this,s)}ln.resolveRef=HU;function UU(t){return(0,xn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ly.call(this,t)}function lT(t){for(let e of this._compilations)if(FU(e,t))return e}ln.getCompilingSchema=lT;function FU(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function BU(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||bl.call(this,t,e)}function bl(t,e){let n=this.opts.uriResolver.parse(e),r=(0,xn._getFullPath)(this.opts.uriResolver,n),o=(0,xn.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return jy.call(this,n,t);let s=(0,xn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=bl.call(this,t,i);return typeof a?.schema!="object"?void 0:jy.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Ly.call(this,i),s===(0,xn.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,xn.resolveUrl)(this.opts.uriResolver,o,u)),new Xs({schema:a,schemaId:c,root:t,baseId:o})}return jy.call(this,n,i)}}ln.resolveSchema=bl;var ZU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function jy(t,{baseId:e,schema:n,root:r}){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 n=="boolean")return;let c=n[(0,uT.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!ZU.has(a)&&u&&(e=(0,xn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,uT.schemaHasRulesButRef)(n,this.RULES)){let a=(0,xn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=bl.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Xs({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var dT=L((NX,qU)=>{qU.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 Uy=L((MX,yT)=>{"use strict";var VU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),mT=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),zy=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),fT=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),WU=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Hy(t){let e="",n=0,r=0;for(r=0;r=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var KU=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function pT(t){return t.length=0,!0}function GU(t,e,n){if(t.length){let r=Hy(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function JU(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=GU;for(let c=0;c7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=pT}else{o.push(u);continue}}return o.length&&(a===pT?n.zone=o.join(""):i?r.push(o.join("")):r.push(Hy(o))),n.address=r.join(""),n}function hT(t){if(XU(t,":")<2)return{host:t,isIPV6:!1};let e=JU(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function XU(t,e){let n=0;for(let r=0;rQU[r])}function nF(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r{"use strict";var{isUUID:iF}=Uy(),aF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,cF=["http","https","ws","wss","urn","urn:uuid"];function uF(t){return cF.indexOf(t)!==-1}function Fy(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 _T(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function bT(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 lF(t){return t.secure=Fy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function dF(t){if((t.port===(Fy(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,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function pF(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(aF);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=By(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function mF(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=By(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function fF(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!iF(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function hF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var xT={scheme:"http",domainHost:!0,parse:_T,serialize:bT},gF={scheme:"https",domainHost:xT.domainHost,parse:_T,serialize:bT},Sl={scheme:"ws",domainHost:!0,parse:lF,serialize:dF},yF={scheme:"wss",domainHost:Sl.domainHost,parse:Sl.parse,serialize:Sl.serialize},_F={scheme:"urn",parse:pF,serialize:mF,skipNormalize:!0},bF={scheme:"urn:uuid",parse:fF,serialize:hF,skipNormalize:!0},vl={http:xT,https:gF,ws:Sl,wss:yF,urn:_F,"urn:uuid":bF};Object.setPrototypeOf(vl,null);function By(t){return t&&(vl[t]||vl[t.toLowerCase()])||void 0}ST.exports={wsIsSecure:Fy,SCHEMES:vl,isValidSchemeName:uF,getSchemeHandler:By}});var PT=L((jX,kl)=>{"use strict";var{normalizeIPv6:xF,removeDotSegments:La,recomposeAuthority:SF,normalizePercentEncoding:vF,normalizePathEncoding:kF,escapePreservingEscapes:wF,reescapeHostDelimiters:EF,isIPv4:TF,nonSimpleDomain:$F}=Uy(),{SCHEMES:PF,getSchemeHandler:wT}=vT();function RF(t,e){return typeof t=="string"?t=NF(t,e):typeof t=="object"&&(t=Ys(Vo(t,e),e)),t}function CF(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=ET(Ys(t,r),Ys(e,r),r,!0);return r.skipEscape=!0,Vo(o,r)}function ET(t,e,n,r){let o={};return r||(t=Ys(Vo(t,n),n),e=Ys(Vo(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=La(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=La(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=La(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=La(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 OF(t,e,n){let r=kT(t,n),o=kT(e,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function Vo(t,e){let n={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:""},r=Object.assign({},e),o=[],s=wT(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=vF(n.path):(n.path=wF(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let i=SF(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=La(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var IF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function AF(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function TT(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(IF);if(i){r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]);let a=AF(r,i);if(a!==void 0&&(r.error=r.error||a,o=!0),r.host)if(TF(r.host)===!1){let l=xF(r.host);r.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let c=wT(n.scheme||r.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&r.host&&(n.domainHost||c&&c.domainHost)&&s===!1&&$F(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(u){r.error=r.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=EF(unescape(r.host),s))),r.path&&(r.path=kF(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}c&&c.parse&&c.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function Ys(t,e){return TT(t,e).parsed}function NF(t,e){return $T(t,e).normalized}function $T(t,e){let{parsed:n,malformedAuthorityOrPort:r}=TT(t,e);return{normalized:r?t:Vo(n,e),malformedAuthorityOrPort:r}}function kT(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=$T(t,e);return r?void 0:n}if(typeof t=="object")return Vo(t,e)}var Zy={SCHEMES:PF,normalize:RF,resolve:CF,resolveComponent:ET,equal:OF,serialize:Vo,parse:Ys};kl.exports=Zy;kl.exports.default=Zy;kl.exports.fastUri=Zy});var CT=L(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var RT=PT();RT.code='require("ajv/dist/runtime/uri").default';qy.default=RT});var LT=L(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.CodeGen=dt.Name=dt.nil=dt.stringify=dt.str=dt._=dt.KeywordCxt=void 0;var MF=Da();Object.defineProperty(dt,"KeywordCxt",{enumerable:!0,get:function(){return MF.KeywordCxt}});var Qs=oe();Object.defineProperty(dt,"_",{enumerable:!0,get:function(){return Qs._}});Object.defineProperty(dt,"str",{enumerable:!0,get:function(){return Qs.str}});Object.defineProperty(dt,"stringify",{enumerable:!0,get:function(){return Qs.stringify}});Object.defineProperty(dt,"nil",{enumerable:!0,get:function(){return Qs.nil}});Object.defineProperty(dt,"Name",{enumerable:!0,get:function(){return Qs.Name}});Object.defineProperty(dt,"CodeGen",{enumerable:!0,get:function(){return Qs.CodeGen}});var DF=_l(),MT=ja(),jF=by(),za=xl(),LF=oe(),Ha=Aa(),wl=Ia(),Wy=me(),OT=dT(),zF=CT(),DT=(t,e)=>new RegExp(t,e);DT.code="new RegExp";var HF=["removeAdditional","useDefaults","coerceTypes"],UF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),FF={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."},BF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},IT=200;function ZF(t){var e,n,r,o,s,i,a,c,u,l,d,p,f,m,h,g,y,_,b,S,T,M,v,$,P;let A=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,C=R===!0||R===void 0?1:R||0,H=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:DT,W=(o=t.uriResolver)!==null&&o!==void 0?o:zF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:A)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:A)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:A)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:A)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:A)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:C,regExp:H}:{optimize:C,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:IT,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:IT,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:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(M=t.validateSchema)!==null&&M!==void 0?M:!0,validateFormats:(v=t.validateFormats)!==null&&v!==void 0?v:!0,unicodeRegExp:($=t.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:W}}var Ua=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...ZF(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new LF.ValueScope({scope:{},prefixes:UF,es5:n,lines:r}),this.logger=JF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jF.getRules)(),AT.call(this,FF,e,"NOT SUPPORTED"),AT.call(this,BF,e,"DEPRECATED","warn"),this._metaOpts=KF.call(this),e.formats&&VF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&WF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),qF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=OT;r==="id"&&(o={...OT},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}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 MT.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,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,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 n=(0,Ha.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){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 n;for(;typeof(n=NT.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new za.SchemaEnv({schema:{},schemaId:r});if(n=za.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=NT.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Ha.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(YF.call(this,r,n),!n)return(0,Wy.eachItem)(r,s=>Vy.call(this,s)),this;e2.call(this,n);let o={...n,type:(0,wl.getJSONTypes)(n.type),schemaType:(0,wl.getJSONTypes)(n.schemaType)};return(0,Wy.eachItem)(r,o.type.length===0?s=>Vy.call(this,s,o):s=>o.type.forEach(i=>Vy.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=jT(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,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;r=(0,Ha.normalizeId)(i||r);let u=Ha.getSchemaRefs.call(this,e,r);return c=new za.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=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):za.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{za.compileSchema.call(this,e)}finally{this.opts=n}}};Ua.ValidationError=DF.default;Ua.MissingRefError=MT.default;dt.default=Ua;function AT(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function NT(t){return t=(0,Ha.normalizeId)(t),this.schemas[t]||this.refs[t]}function qF(){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 VF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function WF(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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function KF(){let t={...this.opts};for(let e of HF)delete t[e];return t}var GF={log(){},warn(){},error(){}};function JF(t){if(t===!1)return GF;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 XF=/^[a-z_$][a-z0-9_$:-]*$/i;function YF(t,e){let{RULES:n}=this;if((0,Wy.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!XF.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Vy(t,e,n){var r;let o=e?.post;if(n&&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===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,wl.getJSONTypes)(e.type),schemaType:(0,wl.getJSONTypes)(e.schemaType)}};e.before?QF.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function QF(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function e2(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=jT(e)),t.validateSchema=this.compile(e,!0))}var t2={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function jT(t){return{anyOf:[t,t2]}}});var zT=L(Ky=>{"use strict";Object.defineProperty(Ky,"__esModule",{value:!0});var n2={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ky.default=n2});var BT=L(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.callRef=Wo.getValidate=void 0;var r2=ja(),HT=un(),jt=oe(),ei=sr(),UT=xl(),El=me(),o2={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=UT.resolveRef.call(c,u,o,n);if(l===void 0)throw new r2.default(r.opts.uriResolver,o,n);if(l instanceof UT.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Tl(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Tl(t,(0,jt._)`${m}.validate`,u,u.$async)}function p(m){let h=FT(t,m);Tl(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,jt.stringify)(m)}:{ref:m}),g=e.name("valid"),y=t.subschema({schema:m,dataTypes:[],schemaPath:jt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function FT(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,jt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Wo.getValidate=FT;function Tl(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ei.default.this:jt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,jt._)`await ${(0,HT.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},h=>{o.if((0,jt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,HT.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,jt._)`${m}.errors`;o.assign(ei.default.vErrors,(0,jt._)`${ei.default.vErrors} === null ? ${h} : ${ei.default.vErrors}.concat(${h})`),o.assign(ei.default.errors,(0,jt._)`${ei.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=n?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=El.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,jt._)`${m}.evaluated.props`);s.props=El.mergeEvaluated.props(o,y,s.props,jt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=El.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,jt._)`${m}.evaluated.items`);s.items=El.mergeEvaluated.items(o,y,s.items,jt.Name)}}}Wo.callRef=Tl;Wo.default=o2});var ZT=L(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var s2=zT(),i2=BT(),a2=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",s2.default,i2.default];Gy.default=a2});var qT=L(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var $l=oe(),Zr=$l.operators,Pl={maximum:{okStr:"<=",ok:Zr.LTE,fail:Zr.GT},minimum:{okStr:">=",ok:Zr.GTE,fail:Zr.LT},exclusiveMaximum:{okStr:"<",ok:Zr.LT,fail:Zr.GTE},exclusiveMinimum:{okStr:">",ok:Zr.GT,fail:Zr.LTE}},c2={message:({keyword:t,schemaCode:e})=>(0,$l.str)`must be ${Pl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$l._)`{comparison: ${Pl[t].okStr}, limit: ${e}}`},u2={keyword:Object.keys(Pl),type:"number",schemaType:"number",$data:!0,error:c2,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,$l._)`${n} ${Pl[e].fail} ${r} || isNaN(${n})`)}};Jy.default=u2});var VT=L(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var Fa=oe(),l2={message:({schemaCode:t})=>(0,Fa.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Fa._)`{multipleOf: ${t}}`},d2={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:l2,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Fa._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Fa._)`${i} !== parseInt(${i})`;t.fail$data((0,Fa._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Xy.default=d2});var KT=L(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});function WT(t){let e=t.length,n=0,r=0,o;for(;r=55296&&o<=56319&&r{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var Ko=oe(),p2=me(),m2=KT(),f2={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Ko.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Ko._)`{limit: ${t}}`},h2={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:f2,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Ko.operators.GT:Ko.operators.LT,i=o.opts.unicode===!1?(0,Ko._)`${n}.length`:(0,Ko._)`${(0,p2.useFunc)(t.gen,m2.default)}(${n})`;t.fail$data((0,Ko._)`${i} ${s} ${r}`)}};Qy.default=h2});var JT=L(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var g2=un(),y2=me(),ti=oe(),_2={message:({schemaCode:t})=>(0,ti.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ti._)`{pattern: ${t}}`},b2={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_2,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ti._)`new RegExp`:(0,y2.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ti._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,ti._)`!${l}`)}else{let c=(0,g2.usePattern)(t,o);t.fail$data((0,ti._)`!${c}.test(${n})`)}}};e_.default=b2});var XT=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var Ba=oe(),x2={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ba.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ba._)`{limit: ${t}}`},S2={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:x2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ba.operators.GT:Ba.operators.LT;t.fail$data((0,Ba._)`Object.keys(${n}).length ${o} ${r}`)}};t_.default=S2});var YT=L(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var Za=un(),qa=oe(),v2=me(),k2={message:({params:{missingProperty:t}})=>(0,qa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,qa._)`{missingProperty: ${t}}`},w2={keyword:"required",type:"object",schemaType:"array",$data:!0,error:k2,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of n)if(f?.[h]===void 0&&!m.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,v2.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(qa.nil,d);else for(let f of n)(0,Za.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Za.checkMissingProp)(t,n,f)),(0,Za.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",r,f=>{t.setParams({missingProperty:f}),e.if((0,Za.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,r,()=>{e.assign(m,(0,Za.propertyInData)(e,o,f,a.ownProperties)),e.if((0,qa.not)(m),()=>{t.error(),e.break()})},qa.nil)}}};n_.default=w2});var QT=L(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var Va=oe(),E2={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Va.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Va._)`{limit: ${t}}`},T2={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:E2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Va.operators.GT:Va.operators.LT;t.fail$data((0,Va._)`${n}.length ${o} ${r}`)}};r_.default=T2});var Rl=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var e$=$y();e$.code='require("ajv/dist/runtime/equal").default';o_.default=e$});var t$=L(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var s_=Ia(),pt=oe(),$2=me(),P2=Rl(),R2={message:({params:{i:t,j:e}})=>(0,pt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pt._)`{i: ${t}, j: ${e}}`},C2={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:R2,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,s_.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,pt._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,pt._)`${n}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,pt._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let g=e.name("item"),y=(0,s_.checkDataTypes)(u,g,a.opts.strictNumbers,s_.DataType.Wrong),_=e.const("indices",(0,pt._)`{}`);e.for((0,pt._)`;${m}--;`,()=>{e.let(g,(0,pt._)`${n}[${m}]`),e.if(y,(0,pt._)`continue`),u.length>1&&e.if((0,pt._)`typeof ${g} == "string"`,(0,pt._)`${g} += "_"`),e.if((0,pt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,pt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,pt._)`${_}[${g}] = ${m}`)})}function f(m,h){let g=(0,$2.useFunc)(e,P2.default),y=e.name("outer");e.label(y).for((0,pt._)`;${m}--;`,()=>e.for((0,pt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,pt._)`${g}(${n}[${m}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};i_.default=C2});var n$=L(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var a_=oe(),O2=me(),I2=Rl(),A2={message:"must be equal to constant",params:({schemaCode:t})=>(0,a_._)`{allowedValue: ${t}}`},N2={keyword:"const",$data:!0,error:A2,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,a_._)`!${(0,O2.useFunc)(e,I2.default)}(${n}, ${o})`):t.fail((0,a_._)`${s} !== ${n}`)}};c_.default=N2});var r$=L(u_=>{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});var Wa=oe(),M2=me(),D2=Rl(),j2={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Wa._)`{allowedValues: ${t}}`},L2={keyword:"enum",schemaType:"array",$data:!0,error:j2,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,M2.useFunc)(e,D2.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Wa.or)(...o.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Wa._)`${u()}(${n}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Wa._)`${u()}(${n}, ${f}[${m}])`:(0,Wa._)`${n} === ${h}`}}};u_.default=L2});var o$=L(l_=>{"use strict";Object.defineProperty(l_,"__esModule",{value:!0});var z2=qT(),H2=VT(),U2=GT(),F2=JT(),B2=XT(),Z2=YT(),q2=QT(),V2=t$(),W2=n$(),K2=r$(),G2=[z2.default,H2.default,U2.default,F2.default,B2.default,Z2.default,q2.default,V2.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},W2.default,K2.default];l_.default=G2});var p_=L(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.validateAdditionalItems=void 0;var Go=oe(),d_=me(),J2={message:({params:{len:t}})=>(0,Go.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Go._)`{limit: ${t}}`},X2={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:J2,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,d_.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}s$(t,r)}};function s$(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Go._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Go._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,d_.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Go._)`${a} <= ${e.length}`);n.if((0,Go.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:d_.Type.Num},u),i.allErrors||n.if((0,Go.not)(u),()=>n.break())})}}Ka.validateAdditionalItems=s$;Ka.default=X2});var m_=L(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.validateTuple=void 0;var i$=oe(),Cl=me(),Y2=un(),Q2={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return a$(t,"additionalItems",e);n.items=!0,!(0,Cl.alwaysValidSchema)(n,e)&&t.ok((0,Y2.validateArray)(t))}};function a$(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Cl.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,i$._)`${s}.length`);n.forEach((d,p)=>{(0,Cl.alwaysValidSchema)(a,d)||(r.if((0,i$._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=n.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Cl.checkStrictMode)(a,g,p.strictTuples)}}}Ga.validateTuple=a$;Ga.default=Q2});var c$=L(f_=>{"use strict";Object.defineProperty(f_,"__esModule",{value:!0});var eB=m_(),tB={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,eB.validateTuple)(t,"items")};f_.default=tB});var l$=L(h_=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});var u$=oe(),nB=me(),rB=un(),oB=p_(),sB={message:({params:{len:t}})=>(0,u$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,u$._)`{limit: ${t}}`},iB={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sB,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,nB.alwaysValidSchema)(r,e)&&(o?(0,oB.validateAdditionalItems)(t,o):t.ok((0,rB.validateArray)(t)))}};h_.default=iB});var d$=L(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});var dn=oe(),Ol=me(),aB={message:({params:{min:t,max:e}})=>e===void 0?(0,dn.str)`must contain at least ${t} valid item(s)`:(0,dn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dn._)`{minContains: ${t}}`:(0,dn._)`{minContains: ${t}, maxContains: ${e}}`},cB={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:aB,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,dn._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ol.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ol.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ol.alwaysValidSchema)(s,n)){let h=(0,dn._)`${l} >= ${i}`;a!==void 0&&(h=(0,dn._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dn._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>m(g)))}function f(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Ol.Type.Num,compositeRule:!0},h),g()})}function m(h){e.code((0,dn._)`${h}++`),a===void 0?e.if((0,dn._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dn._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dn._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};g_.default=cB});var f$=L(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.validateSchemaDeps=Hn.validatePropertyDeps=Hn.error=void 0;var y_=oe(),uB=me(),Ja=un();Hn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,y_.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,y_._)`{property: ${t}, + || ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function QH({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function Oy(t,e,n,r=Xs.Correct){let o=r===Xs.Correct?ne.operators.EQ:ne.operators.NEQ,s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===Xs.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}bt.checkDataType=Oy;function Iy(t,e,n,r){if(t.length===1)return Oy(t[0],e,n,r);let o,s=(0,GT.toHash)(t);if(s.array&&s.object){let i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(let i in s)o=(0,ne.and)(o,Oy(i,e,n,r));return o}bt.checkDataTypes=Iy;var eU={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function Ay(t){let e=tU(t);(0,KH.reportError)(e,eU)}bt.reportTypeError=Ay;function tU(t){let{gen:e,data:n,schema:r}=t,o=(0,GT.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var QT=L(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.assignDefaults=void 0;var Ys=oe(),nU=me();function rU(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)YT(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>YT(t,s,o.default))}_l.assignDefaults=rU;function YT(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Ys._)`${s}${(0,Ys.getProperty)(e)}`;if(o){(0,nU.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ys._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ys._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Ys._)`${a} = ${(0,Ys.stringify)(n)}`)}});var cn=L(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.validateUnion=Ee.validateArray=Ee.usePattern=Ee.callValidateCode=Ee.schemaProperties=Ee.allSchemaProperties=Ee.noPropertyInData=Ee.propertyInData=Ee.isOwnProperty=Ee.hasPropFunc=Ee.reportMissingProp=Ee.checkMissingProp=Ee.checkReportMissingProp=void 0;var Ie=oe(),Ny=me(),Hr=sr(),oU=me();function sU(t,e){let{gen:n,data:r,it:o}=t;n.if(Dy(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ie._)`${e}`},!0),t.error()})}Ee.checkReportMissingProp=sU;function iU({gen:t,data:e,it:{opts:n}},r,o){return(0,Ie.or)(...r.map(s=>(0,Ie.and)(Dy(t,e,s,n.ownProperties),(0,Ie._)`${o} = ${s}`)))}Ee.checkMissingProp=iU;function aU(t,e){t.setParams({missingProperty:e},!0),t.error()}Ee.reportMissingProp=aU;function e0(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ie._)`Object.prototype.hasOwnProperty`})}Ee.hasPropFunc=e0;function My(t,e,n){return(0,Ie._)`${e0(t)}.call(${e}, ${n})`}Ee.isOwnProperty=My;function cU(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} !== undefined`;return r?(0,Ie._)`${o} && ${My(t,e,n)}`:o}Ee.propertyInData=cU;function Dy(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} === undefined`;return r?(0,Ie.or)(o,(0,Ie.not)(My(t,e,n))):o}Ee.noPropertyInData=Dy;function t0(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ee.allSchemaProperties=t0;function uU(t,e){return t0(e).filter(n=>!(0,Ny.alwaysValidSchema)(t,e[n]))}Ee.schemaProperties=uU;function lU({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ie._)`${t}, ${e}, ${r}${o}`:e,d=[[Hr.default.instancePath,(0,Ie.strConcat)(Hr.default.instancePath,s)],[Hr.default.parentData,i.parentData],[Hr.default.parentDataProperty,i.parentDataProperty],[Hr.default.rootData,Hr.default.rootData]];i.opts.dynamicRef&&d.push([Hr.default.dynamicAnchors,Hr.default.dynamicAnchors]);let p=(0,Ie._)`${l}, ${n.object(...d)}`;return c!==Ie.nil?(0,Ie._)`${a}.call(${c}, ${p})`:(0,Ie._)`${a}(${p})`}Ee.callValidateCode=lU;var dU=(0,Ie._)`new RegExp`;function pU({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ie._)`${o.code==="new RegExp"?dU:(0,oU.useFunc)(t,o)}(${n}, ${r})`})}Ee.usePattern=pU;function mU(t){let{gen:e,data:n,keyword:r,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,Ie._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Ny.Type.Num},s),e.if((0,Ie.not)(s),a)})}}Ee.validateArray=mU;function fU(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Ny.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ie._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ie.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ee.validateUnion=fU});var o0=L(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.validateKeywordUsage=Ln.validSchemaType=Ln.funcKeywordCode=Ln.macroKeywordCode=void 0;var $t=oe(),Vo=sr(),hU=cn(),gU=Na();function yU(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=r0(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:$t.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ln.macroKeywordCode=yU;function _U(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;xU(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=r0(r,o,u),d=r.let("valid");t.block$data(d,p),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function p(){if(e.errors===!1)h(),e.modifying&&n0(t),g(()=>t.error());else{let y=e.async?f():m();e.modifying&&n0(t),g(()=>bU(t,y))}}function f(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,$t._)`await `),_=>r.assign(d,!1).if((0,$t._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,$t._)`${_}.errors`),()=>r.throw(_))),y}function m(){let y=(0,$t._)`${l}.errors`;return r.assign(y,null),h($t.nil),y}function h(y=e.async?(0,$t._)`await `:$t.nil){let _=c.opts.passContext?Vo.default.this:Vo.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,$t._)`${y}${(0,hU.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;r.if((0,$t.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}Ln.funcKeywordCode=_U;function n0(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,$t._)`${r.parentData}[${r.parentDataProperty}]`))}function bU(t,e){let{gen:n}=t;n.if((0,$t._)`Array.isArray(${e})`,()=>{n.assign(Vo.default.vErrors,(0,$t._)`${Vo.default.vErrors} === null ? ${e} : ${Vo.default.vErrors}.concat(${e})`).assign(Vo.default.errors,(0,$t._)`${Vo.default.vErrors}.length`),(0,gU.extendErrors)(t)},()=>t.error())}function xU({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function r0(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,$t.stringify)(n)})}function vU(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ln.validSchemaType=vU;function SU({schema:t,opts:e,self:n,errSchemaPath:r},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 "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Ln.validateKeywordUsage=SU});var i0=L(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.extendSubschemaMode=Ur.extendSubschemaData=Ur.getSubschema=void 0;var zn=oe(),s0=me();function kU(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}${(0,zn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,s0.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Ur.getSubschema=kU;function wU(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,zn._)`${e.data}${(0,zn.getProperty)(n)}`,!0);c(p),t.errorPath=(0,zn.str)`${u}${(0,s0.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,zn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof zn.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]}}Ur.extendSubschemaData=wU;function EU(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Ur.extendSubschemaMode=EU});var jy=L((mY,a0)=>{"use strict";a0.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var u0=L((fY,c0)=>{"use strict";var Fr=c0.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};bl(e,r,o,t,"",t)};Fr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Fr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Fr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Fr.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 bl(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in Fr.arrayKeywords)for(var p=0;p{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.getSchemaRefs=Dt.resolveUrl=Dt.normalizeId=Dt._getFullPath=Dt.getFullPath=Dt.inlineRef=void 0;var $U=me(),PU=jy(),RU=u0(),CU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function OU(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ly(t):e?l0(t)<=e:!1}Dt.inlineRef=OU;var IU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ly(t){for(let e in t){if(IU.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Ly)||typeof n=="object"&&Ly(n))return!0}return!1}function l0(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!CU.has(n)&&(typeof t[n]=="object"&&(0,$U.eachItem)(t[n],r=>e+=l0(r)),e===1/0))return 1/0}return e}function d0(t,e="",n){n!==!1&&(e=Qs(e));let r=t.parse(e);return p0(t,r)}Dt.getFullPath=d0;function p0(t,e){return t.serialize(e).split("#")[0]+"#"}Dt._getFullPath=p0;var AU=/#\/?$/;function Qs(t){return t?t.replace(AU,""):""}Dt.normalizeId=Qs;function NU(t,e,n){return n=Qs(n),t.resolve(e,n)}Dt.resolveUrl=NU;var MU=/^[a-z_][-a-z0-9._]*$/i;function DU(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Qs(t[n]||e),s={"":o},i=d0(r,o,!1),a={},c=new Set;return RU(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,g=s[m];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(b){let v=this.opts.uriResolver.resolve;if(b=Qs(g?v(g,b):b),c.has(b))throw l(b);c.add(b);let T=this.refs[b];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?u(d,T.schema,b):b!==Qs(h)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!MU.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,p,f){if(p!==void 0&&!PU(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Dt.getSchemaRefs=DU});var za=L(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var y0=VT(),m0=Ma(),Hy=Cy(),xl=Ma(),jU=QT(),La=o0(),zy=i0(),V=oe(),ee=sr(),LU=Da(),ir=me(),ja=Na();function zU(t){if(x0(t)&&(v0(t),b0(t))){FU(t);return}_0(t,()=>(0,y0.topBoolOrEmptySchema)(t))}Br.validateFunctionCode=zU;function _0({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,r.$async,()=>{t.code((0,V._)`"use strict"; ${f0(n,o)}`),UU(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${HU(o)}`,r.$async,()=>t.code(f0(n,o)).code(s))}function HU(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 UU(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 FU(t){let{schema:e,opts:n,gen:r}=t;_0(t,()=>{n.$comment&&e.$comment&&k0(t),WU(t),r.let(ee.default.vErrors,null),r.let(ee.default.errors,0),n.unevaluated&&BU(t),S0(t),JU(t)})}function BU(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,V._)`${n}.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 f0(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${n} */`:V.nil}function ZU(t,e){if(x0(t)&&(v0(t),b0(t))){qU(t,e);return}(0,y0.boolOrEmptySchema)(t,e)}function b0({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function x0(t){return typeof t.schema!="boolean"}function qU(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&k0(t),KU(t),GU(t);let s=r.const("_errs",ee.default.errors);S0(t,s),r.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function v0(t){(0,ir.checkUnknownRules)(t),VU(t)}function S0(t,e){if(t.opts.jtd)return h0(t,[],!1,e);let n=(0,m0.getSchemaTypes)(t.schema),r=(0,m0.coerceAndCheckDataType)(t,n);h0(t,n,!r,e)}function VU(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function WU(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ir.checkStrictMode)(t,"default is ignored in the schema root")}function KU(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,LU.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function GU(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function k0({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$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)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function JU(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$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._)`${r}.errors`,ee.default.vErrors),s.unevaluated&&XU(t),e.return((0,V._)`${ee.default.errors} === 0`))}function XU({gen:t,evaluated:e,props:n,items:r}){n instanceof V.Name&&t.assign((0,V._)`${e}.props`,n),r instanceof V.Name&&t.assign((0,V._)`${e}.items`,r)}function h0(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ir.schemaHasRulesButRef)(s,l))){o.block(()=>E0(t,"$ref",l.all.$ref.definition));return}c.jtd||YU(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Hy.shouldUseGroup)(s,p)&&(p.type?(o.if((0,xl.checkDataType)(p.type,i,c.strictNumbers)),g0(t,p),e.length===1&&e[0]===p.type&&n&&(o.else(),(0,xl.reportTypeError)(t)),o.endIf()):g0(t,p),a||o.if((0,V._)`${ee.default.errors} === ${r||0}`))}}function g0(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,jU.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,Hy.shouldUseRule)(r,s)&&E0(t,s.keyword,s.definition,e.type)})}function YU(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(QU(t,e),t.opts.allowUnionTypes||eF(t,e),tF(t,t.dataTypes))}function QU(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{w0(t.dataTypes,n)||Uy(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),rF(t,e)}}function eF(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Uy(t,"use allowUnionTypes to allow union type keyword")}function tF(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Hy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>nF(e,i))&&Uy(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function nF(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function w0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function rF(t,e){let n=[];for(let r of t.dataTypes)w0(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Uy(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ir.checkStrictMode)(t,e,t.opts.strictTypes)}var vl=class{constructor(e,n,r){if((0,La.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ir.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",T0(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,La.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,n,r){this.failResult((0,V.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,V.not)(e),void 0,n)}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:n}=this;this.fail((0,V._)`${n} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?ja.reportExtraError:ja.reportError)(this,this.def.error,n)}$dataError(){(0,ja.reportError)(this,this.def.$dataError||ja.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ja.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=V.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=V.nil,n=V.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,V.or)((0,V._)`${o} === undefined`,n)),e!==V.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(r.length){if(!(n instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,V._)`${(0,xl.checkDataTypes)(c,n,s.opts.strictNumbers,xl.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${n})`}return V.nil}}subschema(e,n){let r=(0,zy.getSubschema)(this.it,e);(0,zy.extendSubschemaData)(r,this.it,e),(0,zy.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return ZU(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ir.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ir.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,V.Name)),!0}};Br.KeywordCxt=vl;function E0(t,e,n,r){let o=new vl(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,La.funcKeywordCode)(o,n):"macro"in n?(0,La.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,La.funcKeywordCode)(o,n)}var oF=/^\/(?:[^~]|~0|~1)*$/,sF=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function T0(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!oF.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=sF.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 r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[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,ir.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Br.getData=T0});var Sl=L(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var Fy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};By.default=Fy});var Ha=L(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var Zy=Da(),qy=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Zy.resolveUrl)(e,n,r),this.missingSchema=(0,Zy.normalizeId)((0,Zy.getFullPath)(e,this.missingRef))}};Vy.default=qy});var wl=L(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.resolveSchema=un.getCompilingSchema=un.resolveRef=un.compileSchema=un.SchemaEnv=void 0;var _n=oe(),iF=Sl(),Wo=sr(),bn=Da(),$0=me(),aF=za(),ei=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,bn.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};un.SchemaEnv=ei;function Ky(t){let e=P0.call(this,t);if(e)return e;let n=(0,bn.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new _n.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:iF.default,code:(0,_n._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Wo.default.data,parentData:Wo.default.parentData,parentDataProperty:Wo.default.parentDataProperty,dataNames:[Wo.default.data],dataPathArr:[_n.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,_n.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:_n.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,_n._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,aF.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Wo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Wo.default.self}`,`${Wo.default.scope}`,l)(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:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:h}=u;f.evaluated={props:m instanceof _n.Name?void 0:m,items:h instanceof _n.Name?void 0:h,dynamicProps:m instanceof _n.Name,dynamicItems:h instanceof _n.Name},f.source&&(f.source.evaluated=(0,_n.stringify)(f.evaluated))}return t.validate=f,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)}}un.compileSchema=Ky;function cF(t,e,n){var r;n=(0,bn.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=dF.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new ei({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=uF.call(this,s)}un.resolveRef=cF;function uF(t){return(0,bn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ky.call(this,t)}function P0(t){for(let e of this._compilations)if(lF(e,t))return e}un.getCompilingSchema=P0;function lF(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function dF(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||kl.call(this,t,e)}function kl(t,e){let n=this.opts.uriResolver.parse(e),r=(0,bn._getFullPath)(this.opts.uriResolver,n),o=(0,bn.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return Wy.call(this,n,t);let s=(0,bn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=kl.call(this,t,i);return typeof a?.schema!="object"?void 0:Wy.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Ky.call(this,i),s===(0,bn.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,bn.resolveUrl)(this.opts.uriResolver,o,u)),new ei({schema:a,schemaId:c,root:t,baseId:o})}return Wy.call(this,n,i)}}un.resolveSchema=kl;var pF=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wy(t,{baseId:e,schema:n,root:r}){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 n=="boolean")return;let c=n[(0,$0.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!pF.has(a)&&u&&(e=(0,bn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,$0.schemaHasRulesButRef)(n,this.RULES)){let a=(0,bn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=kl.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new ei({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var R0=L((xY,mF)=>{mF.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 Xy=L((vY,M0)=>{"use strict";var fF=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),O0=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),Gy=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),I0=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),hF=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Jy(t){let e="",n=0,r=0;for(r=0;r=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var gF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function C0(t){return t.length=0,!0}function yF(t,e,n){if(t.length){let r=Jy(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function _F(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=yF;for(let c=0;c7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=C0}else{o.push(u);continue}}return o.length&&(a===C0?n.zone=o.join(""):i?r.push(o.join("")):r.push(Jy(o))),n.address=r.join(""),n}function A0(t){if(bF(t,":")<2)return{host:t,isIPV6:!1};let e=_F(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function bF(t,e){let n=0;for(let r=0;rvF[r])}function wF(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r{"use strict";var{isUUID:PF}=Xy(),RF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,CF=["http","https","ws","wss","urn","urn:uuid"];function OF(t){return CF.indexOf(t)!==-1}function Yy(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 D0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function j0(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 IF(t){return t.secure=Yy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function AF(t){if((t.port===(Yy(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,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function NF(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(RF);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=Qy(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function MF(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=Qy(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function DF(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!PF(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function jF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var L0={scheme:"http",domainHost:!0,parse:D0,serialize:j0},LF={scheme:"https",domainHost:L0.domainHost,parse:D0,serialize:j0},El={scheme:"ws",domainHost:!0,parse:IF,serialize:AF},zF={scheme:"wss",domainHost:El.domainHost,parse:El.parse,serialize:El.serialize},HF={scheme:"urn",parse:NF,serialize:MF,skipNormalize:!0},UF={scheme:"urn:uuid",parse:DF,serialize:jF,skipNormalize:!0},Tl={http:L0,https:LF,ws:El,wss:zF,urn:HF,"urn:uuid":UF};Object.setPrototypeOf(Tl,null);function Qy(t){return t&&(Tl[t]||Tl[t.toLowerCase()])||void 0}z0.exports={wsIsSecure:Yy,SCHEMES:Tl,isValidSchemeName:OF,getSchemeHandler:Qy}});var q0=L((kY,Rl)=>{"use strict";var{normalizeIPv6:FF,removeDotSegments:Ua,recomposeAuthority:BF,normalizePercentEncoding:ZF,normalizePathEncoding:qF,escapePreservingEscapes:VF,reescapeHostDelimiters:WF,isIPv4:KF,nonSimpleDomain:GF}=Xy(),{SCHEMES:JF,getSchemeHandler:F0}=H0();function XF(t,e){return typeof t=="string"?t=o2(t,e):typeof t=="object"&&(t=Pl(Ko(t,e),e)),t}function YF(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=$l(t,r),{parsed:i,malformedAuthorityOrPort:a}=$l(e,r);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=B0(o,i,r,!0);return r.skipEscape=!0,Ko(c,r)}function B0(t,e,n,r){let o={};return r||(t=Pl(Ko(t,n),n),e=Pl(Ko(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ua(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=Ua(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ua(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=Ua(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 QF(t,e,n){let r=U0(t,n),o=U0(e,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function Ko(t,e){let n={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:""},r=Object.assign({},e),o=[],s=F0(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=ZF(n.path):(n.path=VF(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let i=BF(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=Ua(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var e2=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,t2=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,n2=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function r2(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function $l(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(t2);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(n2);if(a!==null){let u=a[1],l=u.replace(/[\t\n\r]/g,"");l.length>=2&&(l.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",o=!0):u.length!==l.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(e2);if(c){r.scheme=c[1],r.userinfo=c[3],r.host=c[4],r.port=parseInt(c[5],10),r.path=c[6]||"",r.query=c[7],r.fragment=c[8],isNaN(r.port)&&(r.port=c[5]);let u=r2(r,c);if(u!==void 0&&(r.error=r.error||u,o=!0),r.host)if(KF(r.host)===!1){let p=FF(r.host);r.host=p.host.toLowerCase(),s=p.isIPV6}else s=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let l=F0(n.scheme||r.scheme);if(!n.unicodeSupport&&(!l||!l.unicodeSupport)&&r.host&&(n.domainHost||l&&l.domainHost)&&s===!1&&GF(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(d){r.error=r.error||"Host's domain name can not be converted to ASCII: "+d}if((!l||l&&!l.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=WF(unescape(r.host),s))),r.path&&(r.path=qF(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}l&&l.parse&&l.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function Pl(t,e){return $l(t,e).parsed}function o2(t,e){return Z0(t,e).normalized}function Z0(t,e){let{parsed:n,malformedAuthorityOrPort:r}=$l(t,e);return{normalized:r?t:Ko(n,e),malformedAuthorityOrPort:r}}function U0(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=Z0(t,e);return r?void 0:n}if(typeof t=="object")return Ko(t,e)}var e_={SCHEMES:JF,normalize:XF,resolve:YF,resolveComponent:B0,equal:QF,serialize:Ko,parse:Pl};Rl.exports=e_;Rl.exports.default=e_;Rl.exports.fastUri=e_});var W0=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var V0=q0();V0.code='require("ajv/dist/runtime/uri").default';t_.default=V0});var t$=L(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.CodeGen=pt.Name=pt.nil=pt.stringify=pt.str=pt._=pt.KeywordCxt=void 0;var s2=za();Object.defineProperty(pt,"KeywordCxt",{enumerable:!0,get:function(){return s2.KeywordCxt}});var ti=oe();Object.defineProperty(pt,"_",{enumerable:!0,get:function(){return ti._}});Object.defineProperty(pt,"str",{enumerable:!0,get:function(){return ti.str}});Object.defineProperty(pt,"stringify",{enumerable:!0,get:function(){return ti.stringify}});Object.defineProperty(pt,"nil",{enumerable:!0,get:function(){return ti.nil}});Object.defineProperty(pt,"Name",{enumerable:!0,get:function(){return ti.Name}});Object.defineProperty(pt,"CodeGen",{enumerable:!0,get:function(){return ti.CodeGen}});var i2=Sl(),Y0=Ha(),a2=Ry(),Fa=wl(),c2=oe(),Ba=Da(),Cl=Ma(),r_=me(),K0=R0(),u2=W0(),Q0=(t,e)=>new RegExp(t,e);Q0.code="new RegExp";var l2=["removeAdditional","useDefaults","coerceTypes"],d2=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),p2={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."},m2={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},G0=200;function f2(t){var e,n,r,o,s,i,a,c,u,l,d,p,f,m,h,g,y,_,b,v,T,M,S,$,P;let A=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,C=R===!0||R===void 0?1:R||0,H=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Q0,W=(o=t.uriResolver)!==null&&o!==void 0?o:u2.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:A)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:A)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:A)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:A)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:A)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:C,regExp:H}:{optimize:C,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:G0,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:G0,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:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(M=t.validateSchema)!==null&&M!==void 0?M:!0,validateFormats:(S=t.validateFormats)!==null&&S!==void 0?S:!0,unicodeRegExp:($=t.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:W}}var Za=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...f2(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new c2.ValueScope({scope:{},prefixes:d2,es5:n,lines:r}),this.logger=x2(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a2.getRules)(),J0.call(this,p2,e,"NOT SUPPORTED"),J0.call(this,m2,e,"DEPRECATED","warn"),this._metaOpts=_2.call(this),e.formats&&g2.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&y2.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),h2.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=K0;r==="id"&&(o={...K0},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}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 Y0.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,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,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 n=(0,Ba.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){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 n;for(;typeof(n=X0.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Fa.SchemaEnv({schema:{},schemaId:r});if(n=Fa.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=X0.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Ba.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(S2.call(this,r,n),!n)return(0,r_.eachItem)(r,s=>n_.call(this,s)),this;w2.call(this,n);let o={...n,type:(0,Cl.getJSONTypes)(n.type),schemaType:(0,Cl.getJSONTypes)(n.schemaType)};return(0,r_.eachItem)(r,o.type.length===0?s=>n_.call(this,s,o):s=>o.type.forEach(i=>n_.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=e$(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,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;r=(0,Ba.normalizeId)(i||r);let u=Ba.getSchemaRefs.call(this,e,r);return c=new Fa.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=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):Fa.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Fa.compileSchema.call(this,e)}finally{this.opts=n}}};Za.ValidationError=i2.default;Za.MissingRefError=Y0.default;pt.default=Za;function J0(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function X0(t){return t=(0,Ba.normalizeId)(t),this.schemas[t]||this.refs[t]}function h2(){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 g2(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function y2(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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function _2(){let t={...this.opts};for(let e of l2)delete t[e];return t}var b2={log(){},warn(){},error(){}};function x2(t){if(t===!1)return b2;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 v2=/^[a-z_$][a-z0-9_$:-]*$/i;function S2(t,e){let{RULES:n}=this;if((0,r_.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!v2.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function n_(t,e,n){var r;let o=e?.post;if(n&&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===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Cl.getJSONTypes)(e.type),schemaType:(0,Cl.getJSONTypes)(e.schemaType)}};e.before?k2.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function k2(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function w2(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=e$(e)),t.validateSchema=this.compile(e,!0))}var E2={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function e$(t){return{anyOf:[t,E2]}}});var n$=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var T2={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};o_.default=T2});var i$=L(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.callRef=Go.getValidate=void 0;var $2=Ha(),r$=cn(),jt=oe(),ni=sr(),o$=wl(),Ol=me(),P2={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=o$.resolveRef.call(c,u,o,n);if(l===void 0)throw new $2.default(r.opts.uriResolver,o,n);if(l instanceof o$.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Il(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Il(t,(0,jt._)`${m}.validate`,u,u.$async)}function p(m){let h=s$(t,m);Il(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,jt.stringify)(m)}:{ref:m}),g=e.name("valid"),y=t.subschema({schema:m,dataTypes:[],schemaPath:jt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function s$(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,jt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Go.getValidate=s$;function Il(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ni.default.this:jt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,jt._)`await ${(0,r$.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},h=>{o.if((0,jt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,r$.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,jt._)`${m}.errors`;o.assign(ni.default.vErrors,(0,jt._)`${ni.default.vErrors} === null ? ${h} : ${ni.default.vErrors}.concat(${h})`),o.assign(ni.default.errors,(0,jt._)`${ni.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=n?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Ol.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,jt._)`${m}.evaluated.props`);s.props=Ol.mergeEvaluated.props(o,y,s.props,jt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Ol.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,jt._)`${m}.evaluated.items`);s.items=Ol.mergeEvaluated.items(o,y,s.items,jt.Name)}}}Go.callRef=Il;Go.default=P2});var a$=L(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var R2=n$(),C2=i$(),O2=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",R2.default,C2.default];s_.default=O2});var c$=L(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var Al=oe(),Zr=Al.operators,Nl={maximum:{okStr:"<=",ok:Zr.LTE,fail:Zr.GT},minimum:{okStr:">=",ok:Zr.GTE,fail:Zr.LT},exclusiveMaximum:{okStr:"<",ok:Zr.LT,fail:Zr.GTE},exclusiveMinimum:{okStr:">",ok:Zr.GT,fail:Zr.LTE}},I2={message:({keyword:t,schemaCode:e})=>(0,Al.str)`must be ${Nl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Al._)`{comparison: ${Nl[t].okStr}, limit: ${e}}`},A2={keyword:Object.keys(Nl),type:"number",schemaType:"number",$data:!0,error:I2,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Al._)`${n} ${Nl[e].fail} ${r} || isNaN(${n})`)}};i_.default=A2});var u$=L(a_=>{"use strict";Object.defineProperty(a_,"__esModule",{value:!0});var qa=oe(),N2={message:({schemaCode:t})=>(0,qa.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,qa._)`{multipleOf: ${t}}`},M2={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:N2,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,qa._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,qa._)`${i} !== parseInt(${i})`;t.fail$data((0,qa._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};a_.default=M2});var d$=L(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});function l$(t){let e=t.length,n=0,r=0,o;for(;r=55296&&o<=56319&&r{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});var Jo=oe(),D2=me(),j2=d$(),L2={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Jo.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Jo._)`{limit: ${t}}`},z2={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:L2,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Jo.operators.GT:Jo.operators.LT,i=o.opts.unicode===!1?(0,Jo._)`${n}.length`:(0,Jo._)`${(0,D2.useFunc)(t.gen,j2.default)}(${n})`;t.fail$data((0,Jo._)`${i} ${s} ${r}`)}};u_.default=z2});var m$=L(l_=>{"use strict";Object.defineProperty(l_,"__esModule",{value:!0});var H2=cn(),U2=me(),ri=oe(),F2={message:({schemaCode:t})=>(0,ri.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ri._)`{pattern: ${t}}`},B2={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:F2,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ri._)`new RegExp`:(0,U2.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ri._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,ri._)`!${l}`)}else{let c=(0,H2.usePattern)(t,o);t.fail$data((0,ri._)`!${c}.test(${n})`)}}};l_.default=B2});var f$=L(d_=>{"use strict";Object.defineProperty(d_,"__esModule",{value:!0});var Va=oe(),Z2={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Va.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Va._)`{limit: ${t}}`},q2={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Z2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Va.operators.GT:Va.operators.LT;t.fail$data((0,Va._)`Object.keys(${n}).length ${o} ${r}`)}};d_.default=q2});var h$=L(p_=>{"use strict";Object.defineProperty(p_,"__esModule",{value:!0});var Wa=cn(),Ka=oe(),V2=me(),W2={message:({params:{missingProperty:t}})=>(0,Ka.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ka._)`{missingProperty: ${t}}`},K2={keyword:"required",type:"object",schemaType:"array",$data:!0,error:W2,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of n)if(f?.[h]===void 0&&!m.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,V2.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ka.nil,d);else for(let f of n)(0,Wa.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Wa.checkMissingProp)(t,n,f)),(0,Wa.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",r,f=>{t.setParams({missingProperty:f}),e.if((0,Wa.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,r,()=>{e.assign(m,(0,Wa.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Ka.not)(m),()=>{t.error(),e.break()})},Ka.nil)}}};p_.default=K2});var g$=L(m_=>{"use strict";Object.defineProperty(m_,"__esModule",{value:!0});var Ga=oe(),G2={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Ga.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Ga._)`{limit: ${t}}`},J2={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:G2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Ga.operators.GT:Ga.operators.LT;t.fail$data((0,Ga._)`${n}.length ${o} ${r}`)}};m_.default=J2});var Ml=L(f_=>{"use strict";Object.defineProperty(f_,"__esModule",{value:!0});var y$=jy();y$.code='require("ajv/dist/runtime/equal").default';f_.default=y$});var _$=L(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});var h_=Ma(),mt=oe(),X2=me(),Y2=Ml(),Q2={message:({params:{i:t,j:e}})=>(0,mt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,mt._)`{i: ${t}, j: ${e}}`},eB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Q2,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,h_.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,mt._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,mt._)`${n}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,mt._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let g=e.name("item"),y=(0,h_.checkDataTypes)(u,g,a.opts.strictNumbers,h_.DataType.Wrong),_=e.const("indices",(0,mt._)`{}`);e.for((0,mt._)`;${m}--;`,()=>{e.let(g,(0,mt._)`${n}[${m}]`),e.if(y,(0,mt._)`continue`),u.length>1&&e.if((0,mt._)`typeof ${g} == "string"`,(0,mt._)`${g} += "_"`),e.if((0,mt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,mt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,mt._)`${_}[${g}] = ${m}`)})}function f(m,h){let g=(0,X2.useFunc)(e,Y2.default),y=e.name("outer");e.label(y).for((0,mt._)`;${m}--;`,()=>e.for((0,mt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,mt._)`${g}(${n}[${m}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};g_.default=eB});var b$=L(__=>{"use strict";Object.defineProperty(__,"__esModule",{value:!0});var y_=oe(),tB=me(),nB=Ml(),rB={message:"must be equal to constant",params:({schemaCode:t})=>(0,y_._)`{allowedValue: ${t}}`},oB={keyword:"const",$data:!0,error:rB,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,y_._)`!${(0,tB.useFunc)(e,nB.default)}(${n}, ${o})`):t.fail((0,y_._)`${s} !== ${n}`)}};__.default=oB});var x$=L(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var Ja=oe(),sB=me(),iB=Ml(),aB={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ja._)`{allowedValues: ${t}}`},cB={keyword:"enum",schemaType:"array",$data:!0,error:aB,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,sB.useFunc)(e,iB.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Ja.or)(...o.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Ja._)`${u()}(${n}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Ja._)`${u()}(${n}, ${f}[${m}])`:(0,Ja._)`${n} === ${h}`}}};b_.default=cB});var v$=L(x_=>{"use strict";Object.defineProperty(x_,"__esModule",{value:!0});var uB=c$(),lB=u$(),dB=p$(),pB=m$(),mB=f$(),fB=h$(),hB=g$(),gB=_$(),yB=b$(),_B=x$(),bB=[uB.default,lB.default,dB.default,pB.default,mB.default,fB.default,hB.default,gB.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yB.default,_B.default];x_.default=bB});var S_=L(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.validateAdditionalItems=void 0;var Xo=oe(),v_=me(),xB={message:({params:{len:t}})=>(0,Xo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xo._)`{limit: ${t}}`},vB={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:xB,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,v_.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}S$(t,r)}};function S$(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Xo._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Xo._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,v_.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Xo._)`${a} <= ${e.length}`);n.if((0,Xo.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:v_.Type.Num},u),i.allErrors||n.if((0,Xo.not)(u),()=>n.break())})}}Xa.validateAdditionalItems=S$;Xa.default=vB});var k_=L(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.validateTuple=void 0;var k$=oe(),Dl=me(),SB=cn(),kB={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return w$(t,"additionalItems",e);n.items=!0,!(0,Dl.alwaysValidSchema)(n,e)&&t.ok((0,SB.validateArray)(t))}};function w$(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Dl.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,k$._)`${s}.length`);n.forEach((d,p)=>{(0,Dl.alwaysValidSchema)(a,d)||(r.if((0,k$._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=n.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Dl.checkStrictMode)(a,g,p.strictTuples)}}}Ya.validateTuple=w$;Ya.default=kB});var E$=L(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var wB=k_(),EB={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,wB.validateTuple)(t,"items")};w_.default=EB});var $$=L(E_=>{"use strict";Object.defineProperty(E_,"__esModule",{value:!0});var T$=oe(),TB=me(),$B=cn(),PB=S_(),RB={message:({params:{len:t}})=>(0,T$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,T$._)`{limit: ${t}}`},CB={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:RB,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,TB.alwaysValidSchema)(r,e)&&(o?(0,PB.validateAdditionalItems)(t,o):t.ok((0,$B.validateArray)(t)))}};E_.default=CB});var P$=L(T_=>{"use strict";Object.defineProperty(T_,"__esModule",{value:!0});var ln=oe(),jl=me(),OB={message:({params:{min:t,max:e}})=>e===void 0?(0,ln.str)`must contain at least ${t} valid item(s)`:(0,ln.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ln._)`{minContains: ${t}}`:(0,ln._)`{minContains: ${t}, maxContains: ${e}}`},IB={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:OB,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,ln._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,jl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,jl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,jl.alwaysValidSchema)(s,n)){let h=(0,ln._)`${l} >= ${i}`;a!==void 0&&(h=(0,ln._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ln._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>m(g)))}function f(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:jl.Type.Num,compositeRule:!0},h),g()})}function m(h){e.code((0,ln._)`${h}++`),a===void 0?e.if((0,ln._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ln._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ln._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};T_.default=IB});var O$=L(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.validateSchemaDeps=Hn.validatePropertyDeps=Hn.error=void 0;var $_=oe(),AB=me(),Qa=cn();Hn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,$_.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,$_._)`{property: ${t}, missingProperty: ${r}, depsCount: ${e}, - deps: ${n}}`};var lB={keyword:"dependencies",type:"object",schemaType:"object",error:Hn.error,code(t){let[e,n]=dB(t);p$(t,e),m$(t,n)}};function dB({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function p$(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ja.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Ja.checkReportMissingProp)(t,u)}):(n.if((0,y_._)`${c} && (${(0,Ja.checkMissingProp)(t,a,s)})`),(0,Ja.reportMissingProp)(t,s),n.else())}}Hn.validatePropertyDeps=p$;function m$(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,uB.alwaysValidSchema)(s,e[a])||(n.if((0,Ja.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}Hn.validateSchemaDeps=m$;Hn.default=lB});var g$=L(__=>{"use strict";Object.defineProperty(__,"__esModule",{value:!0});var h$=oe(),pB=me(),mB={message:"property name must be valid",params:({params:t})=>(0,h$._)`{propertyName: ${t.propertyName}}`},fB={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:mB,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,pB.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,h$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};__.default=fB});var x_=L(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var Il=un(),Sn=oe(),hB=sr(),Al=me(),gB={message:"must NOT have additional properties",params:({params:t})=>(0,Sn._)`{additionalProperty: ${t.additionalProperty}}`},yB={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gB,code(t){let{gen:e,schema:n,parentSchema:r,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,Al.alwaysValidSchema)(i,n))return;let u=(0,Il.allSchemaProperties)(r.properties),l=(0,Il.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Sn._)`${s} === ${hB.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let _=(0,Al.schemaRefOrVal)(i,r.properties,"properties");y=(0,Il.isOwnProperty)(e,_,g)}else u.length?y=(0,Sn.or)(...u.map(_=>(0,Sn._)`${g} === ${_}`)):y=Sn.nil;return l.length&&(y=(0,Sn.or)(y,...l.map(_=>(0,Sn._)`${(0,Il.usePattern)(t,_)}.test(${g})`))),(0,Sn.not)(y)}function f(g){e.code((0,Sn._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){f(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Al.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,Sn.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,Sn.not)(y),()=>e.break()))}}function h(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:Al.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};b_.default=yB});var b$=L(v_=>{"use strict";Object.defineProperty(v_,"__esModule",{value:!0});var _B=Da(),y$=un(),S_=me(),_$=x_(),bB={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&_$.default.code(new _B.KeywordCxt(s,_$.default,"additionalProperties"));let i=(0,y$.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=S_.mergeEvaluated.props(e,(0,S_.toHash)(i),s.props));let a=i.filter(d=>!(0,S_.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,y$.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&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};v_.default=bB});var k$=L(k_=>{"use strict";Object.defineProperty(k_,"__esModule",{value:!0});var x$=un(),Nl=oe(),S$=me(),v$=me(),xB={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,x$.allSchemaProperties)(n),c=a.filter(h=>(0,S$.alwaysValidSchema)(s,n[h]));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 Nl.Name)&&(s.props=(0,v$.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&f(h),s.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,S$.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",r,g=>{e.if((0,Nl._)`${(0,x$.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:v$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Nl._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Nl.not)(l),()=>e.break())})})}}};k_.default=xB});var w$=L(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var SB=me(),vB={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,SB.alwaysValidSchema)(r,n)){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"}};w_.default=vB});var E$=L(E_=>{"use strict";Object.defineProperty(E_,"__esModule",{value:!0});var kB=un(),wB={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kB.validateUnion,error:{message:"must match a schema in anyOf"}};E_.default=wB});var T$=L(T_=>{"use strict";Object.defineProperty(T_,"__esModule",{value:!0});var Ml=oe(),EB=me(),TB={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ml._)`{passingSchemas: ${t.passing}}`},$B={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:TB,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,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 p;(0,EB.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ml._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ml._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ml.Name)})})}}};T_.default=$B});var $$=L($_=>{"use strict";Object.defineProperty($_,"__esModule",{value:!0});var PB=me(),RB={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,PB.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};$_.default=RB});var C$=L(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var Dl=oe(),R$=me(),CB={message:({params:t})=>(0,Dl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Dl._)`{failingKeyword: ${t.ifClause}}`},OB={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:CB,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,R$.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=P$(r,"then"),s=P$(r,"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,Dl.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 p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Dl._)`${l}`):t.setParams({ifClause:l})}}}};function P$(t,e){let n=t.schema[e];return n!==void 0&&!(0,R$.alwaysValidSchema)(t,n)}P_.default=OB});var O$=L(R_=>{"use strict";Object.defineProperty(R_,"__esModule",{value:!0});var IB=me(),AB={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,IB.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};R_.default=AB});var I$=L(C_=>{"use strict";Object.defineProperty(C_,"__esModule",{value:!0});var NB=p_(),MB=c$(),DB=m_(),jB=l$(),LB=d$(),zB=f$(),HB=g$(),UB=x_(),FB=b$(),BB=k$(),ZB=w$(),qB=E$(),VB=T$(),WB=$$(),KB=C$(),GB=O$();function JB(t=!1){let e=[ZB.default,qB.default,VB.default,WB.default,KB.default,GB.default,HB.default,UB.default,zB.default,FB.default,BB.default];return t?e.push(MB.default,jB.default):e.push(NB.default,DB.default),e.push(LB.default),e}C_.default=JB});var A$=L(O_=>{"use strict";Object.defineProperty(O_,"__esModule",{value:!0});var Ve=oe(),XB={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},YB={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XB,code(t,e){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,Ve._)`${m}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Ve._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Ve._)`${h}.type || "string"`).assign(y,(0,Ve._)`${h}.validate`),()=>n.assign(g,(0,Ve._)`"string"`).assign(y,h)),t.fail$data((0,Ve.or)(_(),b()));function _(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${y}`}function b(){let S=l.$async?(0,Ve._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Ve._)`${y}(${r})`,T=(0,Ve._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${r}))`;return(0,Ve._)`${y} && ${y} !== true && ${g} === ${e} && !${T}`}}function f(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[h,g,y]=b(m);h===e&&t.pass(S());function _(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(T){let M=T instanceof RegExp?(0,Ve.regexpCode)(T):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,v=n.scopeValue("formats",{key:s,ref:T,code:M});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Ve._)`${v}.validate`]:["string",T,v]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${y}(${r})`}return typeof g=="function"?(0,Ve._)`${y}(${r})`:(0,Ve._)`${y}.test(${r})`}}}};O_.default=YB});var N$=L(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var QB=A$(),eZ=[QB.default];I_.default=eZ});var M$=L(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.contentVocabulary=ni.metadataVocabulary=void 0;ni.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ni.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var j$=L(A_=>{"use strict";Object.defineProperty(A_,"__esModule",{value:!0});var tZ=ZT(),nZ=o$(),rZ=I$(),oZ=N$(),D$=M$(),sZ=[tZ.default,nZ.default,(0,rZ.default)(),oZ.default,D$.metadataVocabulary,D$.contentVocabulary];A_.default=sZ});var z$=L(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});jl.DiscrError=void 0;var L$;(function(t){t.Tag="tag",t.Mapping="mapping"})(L$||(jl.DiscrError=L$={}))});var U$=L(M_=>{"use strict";Object.defineProperty(M_,"__esModule",{value:!0});var ri=oe(),N_=z$(),H$=xl(),iZ=ja(),aZ=me(),cZ={message:({params:{discrError:t,tagName:e}})=>t===N_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,ri._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},uZ={keyword:"discriminator",type:"object",schemaType:"object",error:cZ,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.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,ri._)`${n}${(0,ri.getProperty)(a)}`);e.if((0,ri._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:N_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,ri._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:N_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,ri.Name),m}function p(){var f;let m={},h=y(o),g=!0;for(let S=0;S{lZ.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 j_=L((Ae,D_)=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.MissingRefError=Ae.ValidationError=Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=Ae.Ajv=void 0;var dZ=LT(),pZ=j$(),mZ=U$(),B$=F$(),fZ=["/properties"],Ll="http://json-schema.org/draft-07/schema",oi=class extends dZ.default{_addVocabularies(){super._addVocabularies(),pZ.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(mZ.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(B$,fZ):B$;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)}};Ae.Ajv=oi;D_.exports=Ae=oi;D_.exports.Ajv=oi;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.default=oi;var hZ=Da();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return hZ.KeywordCxt}});var si=oe();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return si._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return si.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return si.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return si.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return si.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return si.CodeGen}});var gZ=_l();Object.defineProperty(Ae,"ValidationError",{enumerable:!0,get:function(){return gZ.default}});var yZ=ja();Object.defineProperty(Ae,"MissingRefError",{enumerable:!0,get:function(){return yZ.default}})});var X$=L(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.formatNames=Fn.fastFormats=Fn.fullFormats=void 0;function Un(t,e){return{validate:t,compare:e}}Fn.fullFormats={date:Un(W$,U_),time:Un(z_(!0),F_),"date-time":Un(Z$(!0),G$),"iso-time":Un(z_(),K$),"iso-date-time":Un(Z$(),J$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:kZ,"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:CZ,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:wZ,int32:{type:"number",validate:$Z},int64:{type:"number",validate:PZ},float:{type:"number",validate:V$},double:{type:"number",validate:V$},password:!0,binary:!0};Fn.fastFormats={...Fn.fullFormats,date:Un(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,U_),time:Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,F_),"date-time":Un(/^\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,G$),"iso-time":Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,K$),"iso-date-time":Un(/^\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,J$),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};Fn.formatNames=Object.keys(Fn.fullFormats);function _Z(t){return t%4===0&&(t%100!==0||t%400===0)}var bZ=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,xZ=[0,31,28,31,30,31,30,31,31,30,31,30,31];function W$(t){let e=bZ.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&_Z(n)?29:xZ[r])}function U_(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function F_(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function K$(t,e){if(!(t&&e))return;let n=L_.exec(t),r=L_.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t=EZ}function PZ(t){return Number.isInteger(t)}function V$(){return!0}var RZ=/[^\\]\\Z/;function CZ(t){if(RZ.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Y$=L(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.formatLimitDefinition=void 0;var OZ=j_(),vn=oe(),qr=vn.operators,zl={formatMaximum:{okStr:"<=",ok:qr.LTE,fail:qr.GT},formatMinimum:{okStr:">=",ok:qr.GTE,fail:qr.LT},formatExclusiveMaximum:{okStr:"<",ok:qr.LT,fail:qr.GTE},formatExclusiveMinimum:{okStr:">",ok:qr.GT,fail:qr.LTE}},IZ={message:({keyword:t,schemaCode:e})=>(0,vn.str)`should be ${zl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vn._)`{comparison: ${zl[t].okStr}, limit: ${e}}`};ii.formatLimitDefinition={keyword:Object.keys(zl),type:"string",schemaType:"string",$data:!0,error:IZ,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new OZ.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,vn._)`${p}[${c.schemaCode}]`);t.fail$data((0,vn.or)((0,vn._)`typeof ${f} != "object"`,(0,vn._)`${f} instanceof RegExp`,(0,vn._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,vn._)`${i.code.formats}${(0,vn.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,vn._)`${p}.compare(${n}, ${r}) ${zl[o].fail} 0`}},dependencies:["format"]};var AZ=t=>(t.addKeyword(ii.formatLimitDefinition),t);ii.default=AZ});var nP=L((Xa,tP)=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var ai=X$(),NZ=Y$(),B_=oe(),Q$=new B_.Name("fullFormats"),MZ=new B_.Name("fastFormats"),Z_=(t,e={keywords:!0})=>{if(Array.isArray(e))return eP(t,e,ai.fullFormats,Q$),t;let[n,r]=e.mode==="fast"?[ai.fastFormats,MZ]:[ai.fullFormats,Q$],o=e.formats||ai.formatNames;return eP(t,o,n,r),e.keywords&&(0,NZ.default)(t),t};Z_.get=(t,e="full")=>{let r=(e==="fast"?ai.fastFormats:ai.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function eP(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,B_._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}tP.exports=Xa=Z_;Object.defineProperty(Xa,"__esModule",{value:!0});Xa.default=Z_});function DZ(){let t=new rP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,oP.default)(t),t}var rP,oP,Hl,sP=x(()=>{rP=Si(j_(),1),oP=Si(nP(),1);Hl=class{constructor(e){this._ajv=e??DZ()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var Ul,iP=x(()=>{Lo();Ul=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.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(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))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},Sa,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.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},Bs,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function aP(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function cP(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var uP=x(()=>{});var Fl,lP=x(()=>{p0();Lo();sP();ua();iP();uP();Fl=class extends sl{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(xa.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)this._oninitialize(r)),this.setNotificationHandler(sg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(pg,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=xa.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ul(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=d0(this._capabilities,e)}setRequestHandler(e,n){let o=Nr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(rn(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=Ar(Fs,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(K.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let m=Ar(js,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Z(K.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=Ar(Wu,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new Z(K.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){cP(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&aP(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:dE.includes(n)?n:Qh,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"},Mu)}async createMessage(e,n){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 r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.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},mg,n):this.request({method:"sampling/createMessage",params:e},Sa,n)}async elicitInput(e,n){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},Bs,n)}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},Bs,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(K.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},fg,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 q_(t){return!!t&&typeof t=="object"&&pP in t}function mP(t){return t[pP]?.complete}var pP,dP,fP=x(()=>{pP=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(dP||(dP={}))});var hP=x(()=>{});function LZ(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"),!jZ.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function zZ(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 V_(t){let e=LZ(t);return zZ(t,e.warnings),e.isValid}var jZ,gP=x(()=>{jZ=/^[A-Za-z0-9._-]{1,128}$/});var Bl,yP=x(()=>{Bl=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.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,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}}});var Zl=x(()=>{su();su()});function xP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function SP(t){return"_def"in t||"_zod"in t||xP(t)}function W_(t){return typeof t!="object"||t===null||SP(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(xP)}function _P(t){if(t){if(W_(t))return Do(t);if(!SP(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function UZ(t){let e=Nr(t);return e?Object.entries(e).map(([n,r])=>{let o=Dw(r),s=jw(r);return{name:n,description:o,required:!s}}):[]}function Vr(t){let n=Nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Ru(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function bP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ql,HZ,Ya,vP=x(()=>{lP();ua();Xg();Lo();fP();hP();gP();yP();Zl();ql=class{constructor(e,n){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,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Bl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(jo)),this.server.assertCanSetRequestHandler(Vr(Fs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(jo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=Ms(n.inputSchema);return o?Kg(o,{strictUnions:!0,pipeStrategy:"input"}):HZ})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=Ms(n.outputSchema);o&&(r.outputSchema=Kg(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Fs,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new Z(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof Z&&r.code===K.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=Ms(e.inputSchema)??e.inputSchema,i=await $u(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Pu(a);throw new Z(K.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new Z(K.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=Ms(e.outputSchema),s=await $u(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Pu(i);throw new Z(K.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.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(p=>setTimeout(p,l));let d=await r.taskStore.getTask(c);if(!d)throw new Z(K.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vr(Ku)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ku,async e=>{switch(e.params.ref.type){case"ref/prompt":return $E(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return PE(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Ya;let s=Nr(r.argsSchema)?.[e.params.argument.name];if(!q_(s))return Ya;let i=mP(s);if(!i)return Ya;let a=await i(e.params.argument.value,e.params.context);return bP(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return Ya;throw new Z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ya;let s=await o(e.params.argument.value,e.params.context);return bP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(zs)),this.server.assertCanSetRequestHandler(Vr(Hs)),this.server.assertCanSetRequestHandler(Vr(qu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zs,async(e,n)=>{let r=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(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Hs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(qu,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Z(K.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new Z(K.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(Us)),this.server.assertCanSetRequestHandler(Vr(Vu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?UZ(n.argsSchema):void 0}))})),this.server.setRequestHandler(Vu,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=Ms(r.argsSchema),s=await $u(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Pu(c);throw new Z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,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,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,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,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,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=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Do(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=Do(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 q_(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){V_(e);let l={title:n,description:r,inputSchema:_P(o),outputSchema:_P(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"&&V_(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=Do(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Do(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,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(W_(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!W_(n[0])&&(i=n.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=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){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}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},HZ={type:"object",properties:{}};Ya={completion:{values:[],hasMore:!1}}});function FZ(t){return bE.parse(JSON.parse(t))}function kP(t){return JSON.stringify(t)+` -`}var Vl,wP=x(()=>{Lo();Vl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` -`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),FZ(n)}clear(){this._buffer=void 0}}});import EP from"node:process";var Wl,TP=x(()=>{wP();Wl=class{constructor(e=EP.stdin,n=EP.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Vl,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{this.onerror?.(r)}}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(n=>{let r=kP(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var LP={};_e(LP,{PolyglotExecutor:()=>ci,buildPowerShellScriptContent:()=>DP,buildScriptFilename:()=>AP,buildShellScriptContent:()=>MP,buildSpawnOptions:()=>NP,rewriteWindowsBuildTools:()=>jP});import{spawn as $P,execSync as BZ,execFileSync as OP}from"node:child_process";import{mkdtempSync as ZZ,writeFileSync as PP,rmSync as qZ,existsSync as RP}from"node:fs";import{join as Kl,resolve as IP}from"node:path";import{tmpdir as VZ}from"node:os";function AP(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${WZ[t]}`}function NP(t){return{windowsHide:t==="win32"}}function KZ(t){return`'${t.replace(/'/g,"'\\''")}'`}function MP(t,e,n){return n==="win32"||!e?t:`export PATH=${KZ(e)} -${t}`}function GZ(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function DP(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(` -`)}function jP(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",` + deps: ${n}}`};var NB={keyword:"dependencies",type:"object",schemaType:"object",error:Hn.error,code(t){let[e,n]=MB(t);R$(t,e),C$(t,n)}};function MB({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function R$(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Qa.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Qa.checkReportMissingProp)(t,u)}):(n.if((0,$_._)`${c} && (${(0,Qa.checkMissingProp)(t,a,s)})`),(0,Qa.reportMissingProp)(t,s),n.else())}}Hn.validatePropertyDeps=R$;function C$(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,AB.alwaysValidSchema)(s,e[a])||(n.if((0,Qa.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}Hn.validateSchemaDeps=C$;Hn.default=NB});var A$=L(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var I$=oe(),DB=me(),jB={message:"property name must be valid",params:({params:t})=>(0,I$._)`{propertyName: ${t.propertyName}}`},LB={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jB,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,DB.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,I$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};P_.default=LB});var C_=L(R_=>{"use strict";Object.defineProperty(R_,"__esModule",{value:!0});var Ll=cn(),xn=oe(),zB=sr(),zl=me(),HB={message:"must NOT have additional properties",params:({params:t})=>(0,xn._)`{additionalProperty: ${t.additionalProperty}}`},UB={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:HB,code(t){let{gen:e,schema:n,parentSchema:r,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,zl.alwaysValidSchema)(i,n))return;let u=(0,Ll.allSchemaProperties)(r.properties),l=(0,Ll.allSchemaProperties)(r.patternProperties);d(),t.ok((0,xn._)`${s} === ${zB.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let _=(0,zl.schemaRefOrVal)(i,r.properties,"properties");y=(0,Ll.isOwnProperty)(e,_,g)}else u.length?y=(0,xn.or)(...u.map(_=>(0,xn._)`${g} === ${_}`)):y=xn.nil;return l.length&&(y=(0,xn.or)(y,...l.map(_=>(0,xn._)`${(0,Ll.usePattern)(t,_)}.test(${g})`))),(0,xn.not)(y)}function f(g){e.code((0,xn._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){f(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,zl.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,xn.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,xn.not)(y),()=>e.break()))}}function h(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:zl.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};R_.default=UB});var D$=L(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var FB=za(),N$=cn(),O_=me(),M$=C_(),BB={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&M$.default.code(new FB.KeywordCxt(s,M$.default,"additionalProperties"));let i=(0,N$.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=O_.mergeEvaluated.props(e,(0,O_.toHash)(i),s.props));let a=i.filter(d=>!(0,O_.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,N$.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&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};I_.default=BB});var H$=L(A_=>{"use strict";Object.defineProperty(A_,"__esModule",{value:!0});var j$=cn(),Hl=oe(),L$=me(),z$=me(),ZB={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,j$.allSchemaProperties)(n),c=a.filter(h=>(0,L$.alwaysValidSchema)(s,n[h]));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 Hl.Name)&&(s.props=(0,z$.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&f(h),s.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,L$.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",r,g=>{e.if((0,Hl._)`${(0,j$.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:z$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Hl._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Hl.not)(l),()=>e.break())})})}}};A_.default=ZB});var U$=L(N_=>{"use strict";Object.defineProperty(N_,"__esModule",{value:!0});var qB=me(),VB={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,qB.alwaysValidSchema)(r,n)){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"}};N_.default=VB});var F$=L(M_=>{"use strict";Object.defineProperty(M_,"__esModule",{value:!0});var WB=cn(),KB={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:WB.validateUnion,error:{message:"must match a schema in anyOf"}};M_.default=KB});var B$=L(D_=>{"use strict";Object.defineProperty(D_,"__esModule",{value:!0});var Ul=oe(),GB=me(),JB={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ul._)`{passingSchemas: ${t.passing}}`},XB={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:JB,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,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 p;(0,GB.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ul._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ul._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ul.Name)})})}}};D_.default=XB});var Z$=L(j_=>{"use strict";Object.defineProperty(j_,"__esModule",{value:!0});var YB=me(),QB={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,YB.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};j_.default=QB});var W$=L(L_=>{"use strict";Object.defineProperty(L_,"__esModule",{value:!0});var Fl=oe(),V$=me(),eZ={message:({params:t})=>(0,Fl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Fl._)`{failingKeyword: ${t.ifClause}}`},tZ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:eZ,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,V$.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=q$(r,"then"),s=q$(r,"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,Fl.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 p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Fl._)`${l}`):t.setParams({ifClause:l})}}}};function q$(t,e){let n=t.schema[e];return n!==void 0&&!(0,V$.alwaysValidSchema)(t,n)}L_.default=tZ});var K$=L(z_=>{"use strict";Object.defineProperty(z_,"__esModule",{value:!0});var nZ=me(),rZ={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,nZ.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};z_.default=rZ});var G$=L(H_=>{"use strict";Object.defineProperty(H_,"__esModule",{value:!0});var oZ=S_(),sZ=E$(),iZ=k_(),aZ=$$(),cZ=P$(),uZ=O$(),lZ=A$(),dZ=C_(),pZ=D$(),mZ=H$(),fZ=U$(),hZ=F$(),gZ=B$(),yZ=Z$(),_Z=W$(),bZ=K$();function xZ(t=!1){let e=[fZ.default,hZ.default,gZ.default,yZ.default,_Z.default,bZ.default,lZ.default,dZ.default,uZ.default,pZ.default,mZ.default];return t?e.push(sZ.default,aZ.default):e.push(oZ.default,iZ.default),e.push(cZ.default),e}H_.default=xZ});var J$=L(U_=>{"use strict";Object.defineProperty(U_,"__esModule",{value:!0});var Ve=oe(),vZ={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},SZ={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:vZ,code(t,e){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,Ve._)`${m}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Ve._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Ve._)`${h}.type || "string"`).assign(y,(0,Ve._)`${h}.validate`),()=>n.assign(g,(0,Ve._)`"string"`).assign(y,h)),t.fail$data((0,Ve.or)(_(),b()));function _(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${y}`}function b(){let v=l.$async?(0,Ve._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Ve._)`${y}(${r})`,T=(0,Ve._)`(typeof ${y} == "function" ? ${v} : ${y}.test(${r}))`;return(0,Ve._)`${y} && ${y} !== true && ${g} === ${e} && !${T}`}}function f(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[h,g,y]=b(m);h===e&&t.pass(v());function _(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(T){let M=T instanceof RegExp?(0,Ve.regexpCode)(T):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,S=n.scopeValue("formats",{key:s,ref:T,code:M});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Ve._)`${S}.validate`]:["string",T,S]}function v(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${y}(${r})`}return typeof g=="function"?(0,Ve._)`${y}(${r})`:(0,Ve._)`${y}.test(${r})`}}}};U_.default=SZ});var X$=L(F_=>{"use strict";Object.defineProperty(F_,"__esModule",{value:!0});var kZ=J$(),wZ=[kZ.default];F_.default=wZ});var Y$=L(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.contentVocabulary=oi.metadataVocabulary=void 0;oi.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];oi.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var eP=L(B_=>{"use strict";Object.defineProperty(B_,"__esModule",{value:!0});var EZ=a$(),TZ=v$(),$Z=G$(),PZ=X$(),Q$=Y$(),RZ=[EZ.default,TZ.default,(0,$Z.default)(),PZ.default,Q$.metadataVocabulary,Q$.contentVocabulary];B_.default=RZ});var nP=L(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});Bl.DiscrError=void 0;var tP;(function(t){t.Tag="tag",t.Mapping="mapping"})(tP||(Bl.DiscrError=tP={}))});var oP=L(q_=>{"use strict";Object.defineProperty(q_,"__esModule",{value:!0});var si=oe(),Z_=nP(),rP=wl(),CZ=Ha(),OZ=me(),IZ={message:({params:{discrError:t,tagName:e}})=>t===Z_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,si._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},AZ={keyword:"discriminator",type:"object",schemaType:"object",error:IZ,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.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,si._)`${n}${(0,si.getProperty)(a)}`);e.if((0,si._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Z_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,si._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Z_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,si.Name),m}function p(){var f;let m={},h=y(o),g=!0;for(let v=0;v{NZ.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 W_=L((Ae,V_)=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.MissingRefError=Ae.ValidationError=Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=Ae.Ajv=void 0;var MZ=t$(),DZ=eP(),jZ=oP(),iP=sP(),LZ=["/properties"],Zl="http://json-schema.org/draft-07/schema",ii=class extends MZ.default{_addVocabularies(){super._addVocabularies(),DZ.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(jZ.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(iP,LZ):iP;this.addMetaSchema(e,Zl,!1),this.refs["http://json-schema.org/schema"]=Zl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Zl)?Zl:void 0)}};Ae.Ajv=ii;V_.exports=Ae=ii;V_.exports.Ajv=ii;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.default=ii;var zZ=za();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return zZ.KeywordCxt}});var ai=oe();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return ai._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return ai.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return ai.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return ai.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return ai.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return ai.CodeGen}});var HZ=Sl();Object.defineProperty(Ae,"ValidationError",{enumerable:!0,get:function(){return HZ.default}});var UZ=Ha();Object.defineProperty(Ae,"MissingRefError",{enumerable:!0,get:function(){return UZ.default}})});var fP=L(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.formatNames=Fn.fastFormats=Fn.fullFormats=void 0;function Un(t,e){return{validate:t,compare:e}}Fn.fullFormats={date:Un(lP,X_),time:Un(G_(!0),Y_),"date-time":Un(aP(!0),pP),"iso-time":Un(G_(),dP),"iso-date-time":Un(aP(),mP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:WZ,"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:eq,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:KZ,int32:{type:"number",validate:XZ},int64:{type:"number",validate:YZ},float:{type:"number",validate:uP},double:{type:"number",validate:uP},password:!0,binary:!0};Fn.fastFormats={...Fn.fullFormats,date:Un(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,X_),time:Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Y_),"date-time":Un(/^\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,pP),"iso-time":Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,dP),"iso-date-time":Un(/^\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,mP),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};Fn.formatNames=Object.keys(Fn.fullFormats);function FZ(t){return t%4===0&&(t%100!==0||t%400===0)}var BZ=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ZZ=[0,31,28,31,30,31,30,31,31,30,31,30,31];function lP(t){let e=BZ.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&FZ(n)?29:ZZ[r])}function X_(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function Y_(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function dP(t,e){if(!(t&&e))return;let n=K_.exec(t),r=K_.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t=GZ}function YZ(t){return Number.isInteger(t)}function uP(){return!0}var QZ=/[^\\]\\Z/;function eq(t){if(QZ.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var hP=L(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.formatLimitDefinition=void 0;var tq=W_(),vn=oe(),qr=vn.operators,ql={formatMaximum:{okStr:"<=",ok:qr.LTE,fail:qr.GT},formatMinimum:{okStr:">=",ok:qr.GTE,fail:qr.LT},formatExclusiveMaximum:{okStr:"<",ok:qr.LT,fail:qr.GTE},formatExclusiveMinimum:{okStr:">",ok:qr.GT,fail:qr.LTE}},nq={message:({keyword:t,schemaCode:e})=>(0,vn.str)`should be ${ql[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vn._)`{comparison: ${ql[t].okStr}, limit: ${e}}`};ci.formatLimitDefinition={keyword:Object.keys(ql),type:"string",schemaType:"string",$data:!0,error:nq,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new tq.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,vn._)`${p}[${c.schemaCode}]`);t.fail$data((0,vn.or)((0,vn._)`typeof ${f} != "object"`,(0,vn._)`${f} instanceof RegExp`,(0,vn._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,vn._)`${i.code.formats}${(0,vn.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,vn._)`${p}.compare(${n}, ${r}) ${ql[o].fail} 0`}},dependencies:["format"]};var rq=t=>(t.addKeyword(ci.formatLimitDefinition),t);ci.default=rq});var bP=L((ec,_P)=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var ui=fP(),oq=hP(),Q_=oe(),gP=new Q_.Name("fullFormats"),sq=new Q_.Name("fastFormats"),eb=(t,e={keywords:!0})=>{if(Array.isArray(e))return yP(t,e,ui.fullFormats,gP),t;let[n,r]=e.mode==="fast"?[ui.fastFormats,sq]:[ui.fullFormats,gP],o=e.formats||ui.formatNames;return yP(t,o,n,r),e.keywords&&(0,oq.default)(t),t};eb.get=(t,e="full")=>{let r=(e==="fast"?ui.fastFormats:ui.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function yP(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Q_._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}_P.exports=ec=eb;Object.defineProperty(ec,"__esModule",{value:!0});ec.default=eb});function iq(){let t=new xP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,vP.default)(t),t}var xP,vP,Vl,SP=x(()=>{xP=ki(W_(),1),vP=ki(bP(),1);Vl=class{constructor(e){this._ajv=e??iq()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var Wl,kP=x(()=>{Ho();Wl=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.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(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))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},wa,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.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},Vs,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function wP(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function EP(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var TP=x(()=>{});var Kl,$P=x(()=>{CT();Ho();SP();pa();kP();TP();Kl=class extends ul{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ka.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)this._oninitialize(r)),this.setNotificationHandler(hg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Sg,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=ka.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Wl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=RT(this._capabilities,e)}setRequestHandler(e,n){let o=Nr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Ls(o);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=Ar(qs,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(K.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let m=Ar(Hs,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Z(K.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=Ar(Xu,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new Z(K.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){EP(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&wP(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:RE.includes(n)?n:ug,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"},zu)}async createMessage(e,n){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 r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.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},kg,n):this.request({method:"sampling/createMessage",params:e},wa,n)}async elicitInput(e,n){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},Vs,n)}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},Vs,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(K.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},wg,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 tb(t){return!!t&&typeof t=="object"&&RP in t}function CP(t){return t[RP]?.complete}var RP,PP,OP=x(()=>{RP=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(PP||(PP={}))});var IP=x(()=>{});function cq(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"),!aq.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function uq(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 nb(t){let e=cq(t);return uq(t,e.warnings),e.isValid}var aq,AP=x(()=>{aq=/^[A-Za-z0-9._-]{1,128}$/});var Gl,NP=x(()=>{Gl=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.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,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}}});var Jl=x(()=>{lu();lu()});function jP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function LP(t){return"_def"in t||"_zod"in t||jP(t)}function rb(t){return typeof t!="object"||t===null||LP(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(jP)}function MP(t){if(t){if(rb(t))return Lo(t);if(!LP(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function dq(t){let e=Nr(t);return e?Object.entries(e).map(([n,r])=>{let o=eE(r),s=tE(r);return{name:n,description:o,required:!s}}):[]}function Vr(t){let n=Nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Ls(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function DP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Xl,lq,tc,zP=x(()=>{$P();pa();ay();Ho();OP();IP();AP();NP();Jl();Xl=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Kl(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Gl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(zo)),this.server.assertCanSetRequestHandler(Vr(qs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=js(n.inputSchema);return o?oy(o,{strictUnions:!0,pipeStrategy:"input"}):lq})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=js(n.outputSchema);o&&(r.outputSchema=oy(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(qs,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new Z(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof Z&&r.code===K.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=js(e.inputSchema)??e.inputSchema,i=await Iu(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Au(a);throw new Z(K.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new Z(K.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=js(e.outputSchema),s=await Iu(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Au(i);throw new Z(K.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.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(p=>setTimeout(p,l));let d=await r.taskStore.getTask(c);if(!d)throw new Z(K.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vr(Yu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Yu,async e=>{switch(e.params.ref.type){case"ref/prompt":return qE(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return VE(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return tc;let s=Nr(r.argsSchema)?.[e.params.argument.name];if(!tb(s))return tc;let i=CP(s);if(!i)return tc;let a=await i(e.params.argument.value,e.params.context);return DP(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return tc;throw new Z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return tc;let s=await o(e.params.argument.value,e.params.context);return DP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(Fs)),this.server.assertCanSetRequestHandler(Vr(Bs)),this.server.assertCanSetRequestHandler(Vr(Gu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Fs,async(e,n)=>{let r=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(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Bs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Gu,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Z(K.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new Z(K.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(Zs)),this.server.assertCanSetRequestHandler(Vr(Ju)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Zs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?dq(n.argsSchema):void 0}))})),this.server.setRequestHandler(Ju,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=js(r.argsSchema),s=await Iu(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Au(c);throw new Z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,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,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,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,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,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=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Lo(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=Lo(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 tb(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){nb(e);let l={title:n,description:r,inputSchema:MP(o),outputSchema:MP(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"&&nb(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=Lo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Lo(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,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(rb(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!rb(n[0])&&(i=n.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=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){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}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},lq={type:"object",properties:{}};tc={completion:{values:[],hasMore:!1}}});function mq(t){return jE.parse(JSON.parse(t))}function HP(t){return JSON.stringify(t)+` +`}var pq,Yl,UP=x(()=>{Ho();pq=10*1024*1024,Yl=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??pq}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` +`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),mq(n)}clear(){this._buffer=void 0}}});import FP from"node:process";var Ql,BP=x(()=>{UP();Ql=class{constructor(e=FP.stdin,n=FP.stdout,r){this._stdin=e,this._stdout=n,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Yl({maxBufferSize:r?.maxBufferSize})}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(n=>{let r=HP(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var tR={};ye(tR,{PolyglotExecutor:()=>li,buildPowerShellScriptContent:()=>QP,buildScriptFilename:()=>JP,buildShellScriptContent:()=>YP,buildSpawnOptions:()=>XP,rewriteWindowsBuildTools:()=>eR});import{spawn as ZP,execSync as fq,execFileSync as KP}from"node:child_process";import{mkdtempSync as hq,writeFileSync as qP,rmSync as gq,existsSync as VP}from"node:fs";import{join as ed,resolve as GP}from"node:path";import{tmpdir as yq}from"node:os";function JP(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${_q[t]}`}function XP(t){return{windowsHide:t==="win32"}}function bq(t){return`'${t.replace(/'/g,"'\\''")}'`}function YP(t,e,n){return n==="win32"||!e?t:`export PATH=${bq(e)} +${t}`}function xq(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function QP(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(` +`)}function eR(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",` `]),r="",o=!0,s=0;for(;s{"use strict";Yo();Lt=process.platform==="win32",WZ={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};JZ=(()=>{if(Lt)return process.env.TEMP??process.env.TMP??VZ();try{let t=OP(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:IP(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();ci=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Xr()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Lt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=ZZ(Kl(JZ,".ctx-mode-"));try{let c=this.#a(a,r,n),u=Xd(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||CP(a),d}catch(c){throw CP(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=IP(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main +`){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function WP(t){try{gq(t,{recursive:!0,force:!0,maxRetries:Lt?8:2,retryDelay:100})}catch{}}function ob(t){if(Lt&&t.pid)try{fq(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Lt,_q,vq,li,sb=x(()=>{"use strict";es();Lt=process.platform==="win32",_q={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};vq=(()=>{if(Lt)return process.env.TEMP??process.env.TMP??yq();try{let t=KP(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:GP(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();li=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Xr()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Lt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=hq(ed(vq,".ctx-mode-"));try{let c=this.#a(a,r,n),u=rp(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||WP(a),d}catch(c){throw WP(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=GP(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main import "fmt" @@ -508,12 +513,12 @@ func main() { ${n} } `),r==="php"&&!n.trimStart().startsWith(" Enum.each(&Code.prepend_path/1) -${n}`);let o=Kl(e,AP(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=jP(n,process.platform),a=Lt&&GZ(s)?DP(i):i;PP(o,MP(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else PP(o,n,"utf-8");return o}async#c(e,n,r){let o=Lt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{OP("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed: -${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=Lt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;Lt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Lt?e.slice(1).map(b=>b.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!Lt,...NP(process.platform)},d;if(a){let b=[c,...u].map(S=>/\s/.test(S)?JSON.stringify(S):S).join(" ");d=$P(b,[],{...l,shell:!0})}else d=$P(c,u,{...l,shell:!1});let p=!1,f=!1,m=o===void 0?void 0:setTimeout(()=>{if(p=!0,s){f=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let b=Buffer.concat(h).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");i({stdout:b,stderr:S,exitCode:0,timedOut:!0,backgrounded:!0})}else K_(d)},o),h=[],g=[],y=0,_=!1;d.stdout.on("data",b=>{y+=b.length,y<=this.#e?h.push(b):_||(_=!0,K_(d))}),d.stderr.on("data",b=>{y+=b.length,y<=this.#e?g.push(b):_||(_=!0,K_(d))}),d.on("close",b=>{if(clearTimeout(m),f)return;let S=Buffer.concat(h).toString("utf-8"),T=Buffer.concat(g).toString("utf-8");_&&(T+=` -[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:T,exitCode:p?1:b??1,timedOut:p})}),d.on("error",b=>{clearTimeout(m),!f&&i({stdout:"",stderr:b.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=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&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Lt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Lt?"":"/usr/local/bin:/usr/bin:/bin"),Lt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}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=Lt?[]:["/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(RP(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o}; +${n}`);let o=ed(e,JP(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=eR(n,process.platform),a=Lt&&xq(s)?QP(i):i;qP(o,YP(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else qP(o,n,"utf-8");return o}async#c(e,n,r){let o=Lt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{KP("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed: +${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=Lt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;Lt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Lt?e.slice(1).map(b=>b.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!Lt,...XP(process.platform)},d;if(a){let b=[c,...u].map(v=>/\s/.test(v)?JSON.stringify(v):v).join(" ");d=ZP(b,[],{...l,shell:!0})}else d=ZP(c,u,{...l,shell:!1});let p=!1,f=!1,m=o===void 0?void 0:setTimeout(()=>{if(p=!0,s){f=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let b=Buffer.concat(h).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");i({stdout:b,stderr:v,exitCode:0,timedOut:!0,backgrounded:!0})}else ob(d)},o),h=[],g=[],y=0,_=!1;d.stdout.on("data",b=>{y+=b.length,y<=this.#e?h.push(b):_||(_=!0,ob(d))}),d.stderr.on("data",b=>{y+=b.length,y<=this.#e?g.push(b):_||(_=!0,ob(d))}),d.on("close",b=>{if(clearTimeout(m),f)return;let v=Buffer.concat(h).toString("utf-8"),T=Buffer.concat(g).toString("utf-8");_&&(T+=` +[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:v,stderr:T,exitCode:p?1:b??1,timedOut:p})}),d.on("error",b=>{clearTimeout(m),!f&&i({stdout:"",stderr:b.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=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&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Lt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Lt?"":"/usr/local/bin:/usr/bin:/bin"),Lt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}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=Lt?[]:["/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(VP(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o}; const file_path = FILE_CONTENT_PATH; const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8"); ${r}`;case"python":return`FILE_CONTENT_PATH = ${o} @@ -571,29 +576,29 @@ file_content = File.read!(file_content_path) ${r}`;case"csharp":return`var FILE_CONTENT_PATH = ${o}; var file_path = FILE_CONTENT_PATH; var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH); -${r}`}}}});import{cpus as XZ}from"node:os";async function J_(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,XZ().length):s,a=Math.min(s,i,t.length),c=a=t.length)return;try{let m=await t[f].run();u[f]={status:"fulfilled",value:m}}catch(m){u[f]={status:"rejected",reason:m}}o?.(f,u[f])}}let p=[];for(let f=0;f{"use strict"});function X_(t,e){return t===void 0?e:`${t}::${e}`}var HP=x(()=>{"use strict"});function Y_(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n} +${r}`}}}});import{cpus as Sq}from"node:os";async function ib(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,Sq().length):s,a=Math.min(s,i,t.length),c=a=t.length)return;try{let m=await t[f].run();u[f]={status:"fulfilled",value:m}}catch(m){u[f]={status:"rejected",reason:m}}o?.(f,u[f])}}let p=[];for(let f=0;f{"use strict"});function ab(t,e){return t===void 0?e:`${t}::${e}`}var rR=x(()=>{"use strict"});function cb(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n} stdout: ${r} stderr: -${o}`}}var UP=x(()=>{"use strict"});import{execFileSync as YZ}from"node:child_process";function QZ(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=YZ("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function eq(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??QZ,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}function nq(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function rq(t=process.env){let e=Number.parseInt(t.CONTEXT_MODE_BRIDGE_DEPTH??"",10);if(!Number.isFinite(e)||e<=0)return 0;let n=t.CONTEXT_MODE_BRIDGE_IDLE_MS;if(n!==void 0){let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:0}return 18e4}function oq(t){return`[context-mode] Released an idle MCP helper after ${Math.round(t/1e3)}s of inactivity to free memory; it reconnects automatically on next use. (#854)`}function Q_(){Qa=Date.now()}function FP(){Gl++,Qa=Date.now()}function BP(){Gl>0&&Gl--,Qa=Date.now()}function ZP(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{Q_()}catch{}return e(n,r)})}function qP(t){let e=t.checkIntervalMs??nq(),n=t.isParentAlive??tq,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let l of i)process.on(l,o);let a=()=>{n()||o()};process.stdin.isTTY||process.stdin.on("end",a);let c=t.bridgeIdleMs??rq(),u;return c>0&&(Qa=Date.now(),u=setInterval(()=>{Gl===0&&Date.now()-Qa>=c&&(process.stderr.write(oq(c)+` -`),o())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{r=!0,clearInterval(s),u&&clearInterval(u);for(let l of i)process.removeListener(l,o);process.stdin.removeListener("end",a)}}var tq,Qa,Gl,VP=x(()=>{"use strict";tq=eq();Qa=Date.now(),Gl=0});function WP(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}var KP=x(()=>{"use strict"});import{existsSync as eb,unlinkSync as sq}from"node:fs";import{join as ec}from"node:path";function tb(t,e){try{return sq(t),e.push(t),!0}catch{return!1}}function Jl(t,e){let n=!1;for(let r of iq)tb(`${t}${r}`,e)&&r===""&&(n=!0);return n}function GP(t){let{projectDir:e,sessionsDir:n,storePath:r,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=Ii(e),S=rt(e),T=On(e),M=S===T?[S]:[S,T],v=!1;for(let A of M){let R=ec(n,`${A}${b}.db`);if(!eb(R))continue;let C=null;try{C=new Gt({dbPath:R});let H=C.getEvents(a).length;C.deleteSession(a),H>0&&(v=!0)}catch{}finally{try{C?.close()}catch{}}}v&&u.push(`session rows for ${a}`);let $=[];if(r&&eb(r)&&$.push(r),o){let A=rt(e),R=On(e),C=A===R?[A]:[A,R];for(let H of C){let W=ec(o,`${H}.db`);eb(W)&&!$.includes(W)&&$.push(W)}}let P=!1;for(let A of $)try{let R=nt(),C=new R(A,{timeout:3e4});try{let H=C.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;C.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),C.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(P=!0)}finally{try{C.close()}catch{}}}catch{}return P&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let p=!1;if(r&&Jl(r,l)&&(p=!0),o){let b=rt(e),S=On(e),T=b===S?[b]:[b,S];for(let M of T){let v=ec(o,`${M}.db`);Jl(v,l)&&(p=!0)}}if(p&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let b=ec(s,`${i}.db`);Jl(b,l)}let f=Ii(e),m=rt(e),h=On(e),g=m===h?[m]:[m,h],y=!1,_=!1;for(let b of g){let S=ec(n,`${b}${f}`);Jl(`${S}.db`,l)&&(y=!0),tb(`${S}-events.md`,l)&&(_=!0),tb(`${S}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}var iq,JP=x(()=>{"use strict";hr();Jt();iq=["","-wal","-shm"]});import{existsSync as aq}from"node:fs";function nb(t,e){try{if(!aq(t))return;let n=new Gt({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function XP(t){nb(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 YP(t){nb(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 QP(t){nb(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 eR=x(()=>{"use strict";Jt()});import{existsSync as tR}from"node:fs";function nR(t,e,n){try{if(!tR(t))return;let r=new Gt({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function rR(t){try{if(!tR(t))return null;let e=new Gt({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);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 oR=x(()=>{"use strict";Jt()});import{appendFileSync as cq,readFileSync as O7,rmSync as I7}from"node:fs";import{tmpdir as uq}from"node:os";import{basename as lq,join as dq}from"node:path";function pq(t,e=uq()){return dq(e,`context-mode-retrieval-${lq(t)}.txt`)}function sR(t,e,n){if(!(!Number.isFinite(e)||e<=0))try{cq(pq(t,n),`${Math.floor(e)} -`)}catch{}}var iR=x(()=>{"use strict"});import{existsSync as rb,readFileSync as mq,readdirSync as fq,statSync as hq}from"node:fs";import{join as ui,isAbsolute as gq}from"node:path";function uR(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?cR(n,a):null)??r??Be(),l=o?.getMemoryDir(n),d=ui(u,"memory"),p=n?ui(d,rt(n)):d,f=l?cR(n,l):p,m=[];if(n)for(let h of i){let g=ui(n,h);rb(g)&&m.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=ui(u,h);rb(g)&&m.push({path:g,label:`user/${h}`})}if(f&&rb(f))try{let h=fq(f).filter(g=>g.endsWith(".md"));for(let g of h)m.push({path:ui(f,g),label:`memory/${g}`})}catch(h){aR&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h} -`)}for(let h of m){if(s.length>=e)break;try{let g;try{if(g=hq(h.path),g.size>1e6)continue}catch{continue}let y=mq(h.path,"utf-8"),_=y.toLowerCase();for(let b of t){if(s.length>=e)break;let T=b.toLowerCase().split(/\s+/).filter(v=>v.length>=3);if(T.some(v=>{try{return new RegExp(`\\b${v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(v)}})){let v=T.reduce((H,W)=>{let ge=_.indexOf(W);return ge>=0&&(H<0||ge{"use strict"});import{execFileSync as kq}from"node:child_process";function wq(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=kq("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function Eq(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??wq,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}function $q(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function Pq(t=process.env){let e=Number.parseInt(t.CONTEXT_MODE_BRIDGE_DEPTH??"",10);if(!Number.isFinite(e)||e<=0)return 0;let n=t.CONTEXT_MODE_BRIDGE_IDLE_MS;if(n!==void 0){let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:0}return 18e4}function Rq(t){return`[context-mode] Released an idle MCP helper after ${Math.round(t/1e3)}s of inactivity to free memory; it reconnects automatically on next use. (#854)`}function ub(){nc=Date.now()}function sR(){td++,nc=Date.now()}function iR(){td>0&&td--,nc=Date.now()}function aR(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{ub()}catch{}return e(n,r)})}function cR(t){let e=t.checkIntervalMs??$q(),n=t.isParentAlive??Tq,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let l of i)process.on(l,o);let a=()=>{n()||o()};process.stdin.isTTY||process.stdin.on("end",a);let c=t.bridgeIdleMs??Pq(),u;return c>0&&(nc=Date.now(),u=setInterval(()=>{td===0&&Date.now()-nc>=c&&(process.stderr.write(Rq(c)+` +`),o())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{r=!0,clearInterval(s),u&&clearInterval(u);for(let l of i)process.removeListener(l,o);process.stdin.removeListener("end",a)}}var Tq,nc,td,uR=x(()=>{"use strict";Tq=Eq();nc=Date.now(),td=0});function lR(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}var dR=x(()=>{"use strict"});import{existsSync as lb,unlinkSync as Cq}from"node:fs";import{join as rc}from"node:path";function db(t,e){try{return Cq(t),e.push(t),!0}catch{return!1}}function nd(t,e){let n=!1;for(let r of Oq)db(`${t}${r}`,e)&&r===""&&(n=!0);return n}function pR(t){let{projectDir:e,sessionsDir:n,storePath:r,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=Ni(e),v=Ge(e),T=Cn(e),M=v===T?[v]:[v,T],S=!1;for(let A of M){let R=rc(n,`${A}${b}.db`);if(!lb(R))continue;let C=null;try{C=new Jt({dbPath:R});let H=C.getEvents(a).length;C.deleteSession(a),H>0&&(S=!0)}catch{}finally{try{C?.close()}catch{}}}S&&u.push(`session rows for ${a}`);let $=[];if(r&&lb(r)&&$.push(r),o){let A=Ge(e),R=Cn(e),C=A===R?[A]:[A,R];for(let H of C){let W=rc(o,`${H}.db`);lb(W)&&!$.includes(W)&&$.push(W)}}let P=!1;for(let A of $)try{let R=ot(),C=new R(A,{timeout:3e4});try{let H=C.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;C.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),C.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(P=!0)}finally{try{C.close()}catch{}}}catch{}return P&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let p=!1;if(r&&nd(r,l)&&(p=!0),o){let b=Ge(e),v=Cn(e),T=b===v?[b]:[b,v];for(let M of T){let S=rc(o,`${M}.db`);nd(S,l)&&(p=!0)}}if(p&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let b=rc(s,`${i}.db`);nd(b,l)}let f=Ni(e),m=Ge(e),h=Cn(e),g=m===h?[m]:[m,h],y=!1,_=!1;for(let b of g){let v=rc(n,`${b}${f}`);nd(`${v}.db`,l)&&(y=!0),db(`${v}-events.md`,l)&&(_=!0),db(`${v}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}var Oq,mR=x(()=>{"use strict";hr();Ut();Oq=["","-wal","-shm"]});import{existsSync as Iq}from"node:fs";function pb(t,e){try{if(!Iq(t))return;let n=new Jt({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function fR(t){pb(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 hR(t){pb(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 gR(t){pb(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 yR=x(()=>{"use strict";Ut()});import{existsSync as _R}from"node:fs";function bR(t,e,n){try{if(!_R(t))return;let r=new Jt({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function xR(t){try{if(!_R(t))return null;let e=new Jt({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);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 vR=x(()=>{"use strict";Ut()});import{appendFileSync as Aq,readFileSync as yQ,rmSync as _Q}from"node:fs";import{tmpdir as Nq}from"node:os";import{basename as Mq,join as Dq}from"node:path";function jq(t,e=Nq()){return Dq(e,`context-mode-retrieval-${Mq(t)}.txt`)}function SR(t,e,n){if(!(!Number.isFinite(e)||e<=0))try{Aq(jq(t,n),`${Math.floor(e)} +`)}catch{}}var kR=x(()=>{"use strict"});import{existsSync as mb,readFileSync as Lq,readdirSync as zq,statSync as Hq}from"node:fs";import{join as di,isAbsolute as Uq}from"node:path";function TR(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?ER(n,a):null)??r??Be(),l=o?.getMemoryDir(n),d=di(u,"memory"),p=n?di(d,Ge(n)):d,f=l?ER(n,l):p,m=[];if(n)for(let h of i){let g=di(n,h);mb(g)&&m.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=di(u,h);mb(g)&&m.push({path:g,label:`user/${h}`})}if(f&&mb(f))try{let h=zq(f).filter(g=>g.endsWith(".md"));for(let g of h)m.push({path:di(f,g),label:`memory/${g}`})}catch(h){wR&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h} +`)}for(let h of m){if(s.length>=e)break;try{let g;try{if(g=Hq(h.path),g.size>1e6)continue}catch{continue}let y=Lq(h.path,"utf-8"),_=y.toLowerCase();for(let b of t){if(s.length>=e)break;let T=b.toLowerCase().split(/\s+/).filter(S=>S.length>=3);if(T.some(S=>{try{return new RegExp(`\\b${S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(S)}})){let S=T.reduce((H,W)=>{let ge=_.indexOf(W);return ge>=0&&(H<0||ge=0&&($=A+2),R>=0&&(P=R);let C=y.slice($,P).trim();s.push({title:`[auto-memory] ${h.label}`,content:C,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){aR&&process.stderr.write(`[ctx] auto-memory file read failed: ${g} -`)}}return s.slice(0,e)}function cR(t,e){return e?gq(e)||!t?e:ui(t,e):t??""}var aR,lR=x(()=>{"use strict";Sr();Jt();aR=process.env.DEBUG?.includes("context-mode")});function dR(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,p=[],f=new Date().toISOString(),m;if(typeof d=="string"&&a)try{m=new Set(a.getSessionIdsForProject(d))}catch(h){Xl&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h} -`)}try{let h=r.searchWithFallback(e,n,s,i,"like",m);p.push(...h.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||f,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(h){Xl&&process.stderr.write(`[ctx] ContentStore search failed: ${h} -`)}if(o==="timeline"){try{if(a){let h=a.searchEvents(e,n,c||"",s);p.push(...h.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(h){Xl&&process.stderr.write(`[ctx] SessionDB search failed: ${h} -`)}try{let h=uR([e],n,c,u,l);p.push(...h)}catch(h){Xl&&process.stderr.write(`[ctx] auto-memory search failed: ${h} -`)}}for(let h of p)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((h,g)=>(h.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,n)}var Xl,pR=x(()=>{"use strict";lR();Xl=process.env.DEBUG?.includes("context-mode")});function yq(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function mR(t){let e=t?{project:j.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). : scope to that specific project directory.")}:{};return j.object({queries:j.preprocess(yq,j.array(j.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:j.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:j.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:j.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:j.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 fR(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var ob,hR=x(()=>{"use strict";Zl();ob=!!process.env.CONTEXT_MODE_PROJECT_DIR});var Yl,gR=x(()=>{"use strict";Yl=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStartn&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Je.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Je.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(` -`).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(r)}}catch{}}function Sq(t){let e=t?.codexHome??process.env.CODEX_HOME??li.join(yR.homedir(),".codex"),n=li.join(e,"sessions");if(!Je.existsSync(n))return null;let r=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 p of d){if(s>=o)return;s++;let f=li.join(u,p),m;try{m=Je.statSync(f)}catch{continue}if(m.isDirectory()){la&&(a=h,i=f)}};try{c(n,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),p=l.subarray(0,d).toString("utf-8");for(let f of p.split(` -`).slice(0,10))if(f.trim())try{let m=JSON.parse(f),h=m?.meta?.cwd??(m?.type==="session_meta"?m?.payload?.cwd:void 0);if(typeof h!="string"||h.length===0)continue;return Ql(h)?null:h}catch{return null}}finally{Je.closeSync(u)}}catch{return null}return null}function _R(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...lm(a),..._q]:bq;for(let l of u){let d=e[l];if(d&&!Ql(d))return d}if(o){let l=xq({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Ql(l))return l}if(a==="codex"){let l=Sq({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!Ql(r)?r:n}var _q,bq,bR=x(()=>{"use strict";uo();_q=["CONTEXT_MODE_PROJECT_DIR"],bq=["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 vq}from"node:child_process";import{existsSync as ar,readdirSync as di,statSync as kq}from"node:fs";import{homedir as sd}from"node:os";import{join as qt,sep as wq}from"node:path";function $R(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function Tq(t){let e=t?.home??sd();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=qt(e,...o,"context-mode");return{name:r,sessionsDir:qt(s,"sessions"),contentDir:qt(s,"content")}})}function $q(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function tc(t){let e=Be(),n=t?.sessionsDir??qt(e,"context-mode","sessions"),r=t?.memoryRoot??qt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(ar(n)){let f=[];try{f=di(n).filter(m=>m.endsWith(".db"))}catch{}if(f.length>0){let m=null;try{m=t?.loadDatabase?t.loadDatabase():nt()}catch{}if(m)for(let h of f){let g=qt(n,h);try{let y=new m(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 S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let T of S)T.category&&(u[T.category]=(u[T.category]??0)+(T.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let T=S.t.endsWith("Z")?S.t:S.t+"Z",M=Date.parse(T);Number.isFinite(M)&&M{try{return kq(qt(r,m)).isDirectory()}catch{return!1}})}catch{}for(let m of f){let h=qt(r,m,"memory");if(!ar(h))continue;let g=[];try{g=di(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=$q(y);p[_]=(p[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:p,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function PR(t){let e=t.sessionsDir??qt(sd(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!ar(e))return r;let o=[];try{o=di(e).filter(b=>!(!b.endsWith(".db")||t.worktreeHash&&!b.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():nt()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,p=0,f=0,m=new Map,h=b=>Math.floor(b/864e5)*864e5;for(let b of o){let S=qt(e,b),T=!1;try{let M=new s(S,{readonly:!0});try{let v=M.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let P of v)P.category&&(i[P.category]=(i[P.category]??0)+(P.cnt??0),a+=P.cnt??0,T=!0);let $=M.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if($?.mn){let P=Date.parse($.mn+($.mn.endsWith("Z")?"":"Z"));Number.isFinite(P)&&Pp&&(p=P)}try{let P=M.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let A of P){if(!A.sec)continue;let R=parseInt(A.sec,10)*1e3;if(!Number.isFinite(R))continue;let C=h(R),H=m.get(C)??{count:0,rescueBytes:0};H.count+=A.cnt??0,m.set(C,H)}}catch{}try{let P=M.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(n);if(P?.bytes&&(u+=P.bytes),P?.n&&(l+=P.n),P?.lastSec){let A=parseInt(P.lastSec,10)*1e3;if(Number.isFinite(A)&&A>f&&(f=A),Number.isFinite(A)&&(P?.bytes??0)>0){let R=h(A),C=m.get(R)??{count:0,rescueBytes:0};C.rescueBytes=Math.max(C.rescueBytes,P.bytes),m.set(R,C)}}}catch{}}finally{M.close()}}catch{}T&&c++}let g=db>0).map(([b,S])=>({category:b,count:S,label:td[b]||b})).sort((b,S)=>S.count-b.count),_=[...m.entries()].sort((b,S)=>b[0]-S[0]).map(([b,S])=>({ms:b,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:p>0?p:0,lastRescueMs:f>0?f:void 0,byDay:_}}function Pq(t,e,n){if(!t||!e||!ar(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():nt()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes - FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function RR(t,e){if(!t||!ar(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():nt()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes - FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function nd(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??qt(sd(),".claude","context-mode","sessions");if(!ar(n))return e;let r=[];try{r=di(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():nt()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let p=qt(n,d);sp(p,o);try{let f=new o(p,{readonly:!0});try{if(t.sessionId){let m=f.prepare(`SELECT +`,P);A>=0&&($=A+2),R>=0&&(P=R);let C=y.slice($,P).trim();s.push({title:`[auto-memory] ${h.label}`,content:C,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){wR&&process.stderr.write(`[ctx] auto-memory file read failed: ${g} +`)}}return s.slice(0,e)}function ER(t,e){return e?Uq(e)||!t?e:di(t,e):t??""}var wR,$R=x(()=>{"use strict";vr();Ut();wR=process.env.DEBUG?.includes("context-mode")});function PR(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,p=[],f=new Date().toISOString(),m;if(typeof d=="string"&&a)try{m=new Set(a.getSessionIdsForProject(d))}catch(h){rd&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h} +`)}try{let h=r.searchWithFallback(e,n,s,i,"like",m);p.push(...h.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||f,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(h){rd&&process.stderr.write(`[ctx] ContentStore search failed: ${h} +`)}if(o==="timeline"){try{if(a){let h=a.searchEvents(e,n,c||"",s);p.push(...h.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(h){rd&&process.stderr.write(`[ctx] SessionDB search failed: ${h} +`)}try{let h=TR([e],n,c,u,l);p.push(...h)}catch(h){rd&&process.stderr.write(`[ctx] auto-memory search failed: ${h} +`)}}for(let h of p)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((h,g)=>(h.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,n)}var rd,RR=x(()=>{"use strict";$R();rd=process.env.DEBUG?.includes("context-mode")});function Fq(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function CR(t){let e=t?{project:j.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). : scope to that specific project directory.")}:{};return j.object({queries:j.preprocess(Fq,j.array(j.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:j.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:j.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:j.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:j.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 OR(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var fb,IR=x(()=>{"use strict";Jl();fb=!!process.env.CONTEXT_MODE_PROJECT_DIR});var od,AR=x(()=>{"use strict";od=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStartn&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Ye.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Ye.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(` +`).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{Ye.closeSync(r)}}catch{}}function Vq(t){let e=t?.codexHome??process.env.CODEX_HOME??pi.join(NR.homedir(),".codex"),n=pi.join(e,"sessions");if(!Ye.existsSync(n))return null;let r=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Ye.readdirSync(u)}catch{return}d.sort().reverse();for(let p of d){if(s>=o)return;s++;let f=pi.join(u,p),m;try{m=Ye.statSync(f)}catch{continue}if(m.isDirectory()){la&&(a=h,i=f)}};try{c(n,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Ye.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Ye.readSync(u,l,0,l.length,0),p=l.subarray(0,d).toString("utf-8");for(let f of p.split(` +`).slice(0,10))if(f.trim())try{let m=JSON.parse(f),h=m?.meta?.cwd??(m?.type==="session_meta"?m?.payload?.cwd:void 0);if(typeof h!="string"||h.length===0)continue;return sd(h)?null:h}catch{return null}}finally{Ye.closeSync(u)}}catch{return null}return null}function MR(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...xm(a),...Bq]:Zq;for(let l of u){let d=e[l];if(d&&!sd(d))return d}if(o){let l=qq({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!sd(l))return l}if(a==="codex"){let l=Vq({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!sd(r)?r:n}var Bq,Zq,DR=x(()=>{"use strict";po();Bq=["CONTEXT_MODE_PROJECT_DIR"],Zq=["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 Wq}from"node:child_process";import{existsSync as ar,readdirSync as mi,statSync as Kq}from"node:fs";import{homedir as dd}from"node:os";import{join as Vt,sep as Gq}from"node:path";function ZR(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function Xq(t){let e=t?.home??dd();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=Vt(e,...o,"context-mode");return{name:r,sessionsDir:Vt(s,"sessions"),contentDir:Vt(s,"content")}})}function Yq(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function oc(t){let e=Be(),n=t?.sessionsDir??Vt(e,"context-mode","sessions"),r=t?.memoryRoot??Vt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(ar(n)){let f=[];try{f=mi(n).filter(m=>m.endsWith(".db"))}catch{}if(f.length>0){let m=null;try{m=t?.loadDatabase?t.loadDatabase():ot()}catch{}if(m)for(let h of f){let g=Vt(n,h);try{let y=new m(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 T of v)T.category&&(u[T.category]=(u[T.category]??0)+(T.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 T=v.t.endsWith("Z")?v.t:v.t+"Z",M=Date.parse(T);Number.isFinite(M)&&M{try{return Kq(Vt(r,m)).isDirectory()}catch{return!1}})}catch{}for(let m of f){let h=Vt(r,m,"memory");if(!ar(h))continue;let g=[];try{g=mi(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=Yq(y);p[_]=(p[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:p,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function qR(t){let e=t.sessionsDir??Vt(dd(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!ar(e))return r;let o=[];try{o=mi(e).filter(b=>!(!b.endsWith(".db")||t.worktreeHash&&!b.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():ot()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,p=0,f=0,m=new Map,h=b=>Math.floor(b/864e5)*864e5;for(let b of o){let v=Vt(e,b),T=!1;try{let M=new s(v,{readonly:!0});try{let S=M.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let P of S)P.category&&(i[P.category]=(i[P.category]??0)+(P.cnt??0),a+=P.cnt??0,T=!0);let $=M.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if($?.mn){let P=Date.parse($.mn+($.mn.endsWith("Z")?"":"Z"));Number.isFinite(P)&&Pp&&(p=P)}try{let P=M.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let A of P){if(!A.sec)continue;let R=parseInt(A.sec,10)*1e3;if(!Number.isFinite(R))continue;let C=h(R),H=m.get(C)??{count:0,rescueBytes:0};H.count+=A.cnt??0,m.set(C,H)}}catch{}try{let P=M.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(n);if(P?.bytes&&(u+=P.bytes),P?.n&&(l+=P.n),P?.lastSec){let A=parseInt(P.lastSec,10)*1e3;if(Number.isFinite(A)&&A>f&&(f=A),Number.isFinite(A)&&(P?.bytes??0)>0){let R=h(A),C=m.get(R)??{count:0,rescueBytes:0};C.rescueBytes=Math.max(C.rescueBytes,P.bytes),m.set(R,C)}}}catch{}}finally{M.close()}}catch{}T&&c++}let g=db>0).map(([b,v])=>({category:b,count:v,label:ad[b]||b})).sort((b,v)=>v.count-b.count),_=[...m.entries()].sort((b,v)=>b[0]-v[0]).map(([b,v])=>({ms:b,count:v.count,...v.rescueBytes>0?{rescueBytes:v.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:p>0?p:0,lastRescueMs:f>0?f:void 0,byDay:_}}function Qq(t,e,n){if(!t||!e||!ar(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():ot()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes + FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function VR(t,e){if(!t||!ar(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():ot()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes + FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function cd(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??Vt(dd(),".claude","context-mode","sessions");if(!ar(n))return e;let r=[];try{r=mi(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():ot()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let p=Vt(n,d);dp(p,o);try{let f=new o(p,{readonly:!0});try{if(t.sessionId){let m=f.prepare(`SELECT COALESCE(SUM(LENGTH(data)), 0) AS data_bytes, COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided, COALESCE(SUM(bytes_returned), 0) AS bytes_returned @@ -619,48 +624,48 @@ ${o}`}}var UP=x(()=>{"use strict"});import{execFileSync as YZ}from"node:child_pr COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided, COALESCE(SUM(bytes_returned), 0) AS bytes_returned FROM session_events`).get();m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.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{}try{let h=f.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls - WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();h?.bytes&&(a+=Number(h.bytes))}catch{}}}finally{f.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=Pq(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 sb(t){let e=nd({worktreeHash:t.worktreeHash,sessionsDir:t.sessionsDir}),n=nd({sessionId:t.sessionId,worktreeHash:t.worktreeHash,sessionsDir:t.sessionsDir,contentDbPath:t.contentDbPath}),r=n.bytesReturned,o=e.bytesAvoided+e.bytesReturned,s=Math.max(0,o-r);return{eventDataBytes:e.eventDataBytes,bytesAvoided:s,bytesReturned:r,snapshotBytes:e.snapshotBytes,contentBytes:n.contentBytes,totalSavedTokens:Math.floor((e.eventDataBytes+s+e.snapshotBytes)/4)}}function Cq(t,e,n){let r={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(!ar(t.sessionsDir))return r;let o=[];try{o=di(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=qt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let f=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(r.eventCount+=Number(f.cnt??0),r.dataBytes+=Number(f.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.sessionCount+=Number(m?.cnt??0)}catch{}try{let m=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();m?.bytes&&(r.rescueBytes+=Number(m.bytes))}catch{}try{let m=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(m?.mn){let h=Date.parse(m.mn+(m.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&hr.lastMs&&(r.lastMs=h)}}catch{}try{let m=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of m)h.p&&i.add(h.p)}catch{}try{let m=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of m)h.s&&a.add(h.s)}catch{}}finally{p.close()}}catch{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function id(t){let e=Tq({home:t?.home}),n=t?.loadDatabase??nt,r={...Rq,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!ar(c.sessionsDir))continue;let u=Cq(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function rd(t){return Oq[t]??t}function mt(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 n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function Iq(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function ed(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function Aq(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!ed(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=vq("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!ed(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!ed(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return ed(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function xR(t){let e=sd();return e?t===e?"~":t.startsWith(e+wq)?"~"+t.slice(e.length):t:t}function Nq(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*nc(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),f=(e*1/1e6).toFixed(2),m=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,h=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return m&&h?g.push(` $${o(r)} of ${h} tokens your team didn't burn.`):m?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${mt(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.`)),m||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function Mq(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*ER,f=Math.round((e.snapshotBytes??0)/4),m=p+f,h=o?.conversation?.totalSavedTokens??0,g=Math.max(m,h),y=(n?.totalEvents??0)*ER,_=Math.round((n?.rescueBytes??0)/4),b=y+_,S=o?.lifetime?.totalSavedTokens??0,T=Math.max(b,S),M=o?.lifetime?.bytesReturned??0,v=o?.lifetime?.bytesAvoided??0,$=M+v>0?Math.max(1,Math.floor(M/4)):Math.max(1,Math.round(T*.02)),P=r?.totalBytes&&r.totalBytes>0?r.totalBytes:T*4,A=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`,C=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=C>0?Math.max(1,Math.round((c-C)/864e5)):0,W=r?.totalSessions??n?.totalSessions??1,ge=r?.perAdapter.filter(Fe=>Fe.isReal).length??0,Le;if(r&&ge>=2)Le=`across ${ge} AI tools`;else if(r&&ge===1){let Fe=r.perAdapter.find(pn=>pn.isReal);Le=`in ${Fe?rd(Fe.name):"Claude Code"}`}else Le="in Claude Code";H>0?d.push(` Across ${H} days you ran ${kn(W)} conversations ${Le}.`):d.push(` You ran ${kn(W)} conversations ${Le}.`);let st=H>0?P/H:0;d.push(` context-mode kept ${mt(P)} out of your context window \u2014 about ${mt(st)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let $n=e.firstEventMs&&e.firstEventMs>0?SR(e.firstEventMs,i,a):"";if($n?d.push(` This conversation started ${$n} in ${xR(s)}.`):d.push(` This conversation lives in ${xR(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Fe=e.lastRescueMs&&e.lastRescueMs>0?SR(e.lastRescueMs,i,a):"",pn=Math.round(e.snapshotBytes/1024);Fe?d.push(` On ${Fe}, /compact fired \u2014 ${pn} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${pn} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let dc=o?.conversation,pc=dc?.bytesAvoided??0,Od=dc?.bytesReturned??0;if(pc+Od===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Fe=pc+Od,pn=Math.max(1,Od),mn=Math.max(1,Math.floor(Fe/4)),Vn=Math.max(1,Math.floor(pn/4)),Id=Wr(mn,mn,32),XC=Wr(Vn,mn,32),YC=(1-Vn/mn)*100,QC=Math.max(1,Math.round(mn/Vn));d.push(` Without context-mode ${mt(Fe).padStart(8)} ${Id} ${kn(mn).padStart(7)} tokens`),d.push(` With context-mode ${mt(pn).padStart(8)} ${XC} ${kn(Vn).padStart(7)} tokens`),d.push(` ${YC.toFixed(1)}% kept out of context \xB7 your AI ran ${QC}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Fe=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${mt(A)} built up \u2014 ${Fe} days, ${e.byDay.length} active:`),d.push(""),d.push(...jq(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 WC=e.byCategory.reduce((Fe,pn)=>Fe+pn.count,0).toLocaleString(i);d.push(` ${WC} things \u2014 files, errors, decisions, agent runs:`),d.push("");let KC=e.byCategory[0]?.count??1;for(let Fe of e.byCategory)d.push(` ${Fe.label.padEnd(26)} ${String(Fe.count).padStart(5)} ${Wr(Fe.count,KC,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let $b=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Pb=C>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(C)):"",Rb=n?.distinctProjects??0,GC=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${mt(A)} kept out \xB7 ${e.events.toLocaleString(i)} captures${$b?` \xB7 started ${$b}`:""}.`),d.push(` All your work: ${mt(P)} kept out \xB7 ${GC.toLocaleString(i)} captures across ${Rb} project${Rb===1?"":"s"}${Pb?` \xB7 since ${Pb}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...Nq(P,T,H)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Fe=Object.entries(n.autoMemoryByPrefix).sort((mn,Vn)=>Vn[1]-mn[1]),pn=Fe.length>0?Fe[0][1]:1;for(let[mn,Vn]of Fe){let Id=CR[mn]??mn;d.push(` ${Id.padEnd(26)} ${String(Vn).padStart(2)} ${Wr(Vn,pn,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 JC=u?`v${u}`:"context-mode";return d.push(` ${JC}`),u&&l&&l!=="unknown"&&$R(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),Dq(d)}function Dq(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function jq(t,e,n){if(t.length===0)return[];let r=[...t].sort((p,f)=>p.ms-f.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let p of r)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of r){let f=Math.round((p.ms-o.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[f]=m}let l=p=>{let f=new Intl.DateTimeFormat(e,{timeZone:n,month:"short",day:"numeric"}).formatToParts(new Date(p)),m=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${m} ${h}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of r){let f=l(p.ms).padEnd(7),m=`${p.count} captures`,h=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${f} ${m}${h}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function SR(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),s=d=>o.find(p=>p.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} (${n})`}function kn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function nc(){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 5/1e6}function od(t){return`$${((Number.isFinite(t)&&t>0?t:0)*nc()).toFixed(2)}`}function Wr(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function vR(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=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 ${kn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${kn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&n>0?1:c,g=h===1?"1 session":`${kn(h)} sessions`,y=a*256+n;o.push(` ${kn(a)} events \xB7 ${g} \xB7 ~${od(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:td[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let p=d.slice(0,r),f=p.length>0?p[0].count:1;for(let h of p)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${Wr(h.count,f,30)}`);let m=Math.max(0,d.length-r);return m>0&&o.push(` ... ${m} more categor${m===1?"y":"ies"}`),o}function kR(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 n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=CR[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Wr(s,r,20)}`)}return e}function wR(t,e){let n=[],r=od(t),o=(e?.totalEvents??0)*256+t,s=od(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}function TR(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.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?kn(u.eventCount):"\u2014",p=mt(u.dataBytes),f=mt(l);r.push(` ${rd(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${f.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>rd(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function ad(t,e,n,r){let o=[],s=Iq(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(M=>M.isReal).length??0;if(l&&d>0){let M=l.totalSessions||i?.totalSessions||0,v=i?.firstEventMs??0,$=v>0?Math.max(1,Math.round((Date.now()-v)/864e5)):0,P=$>0?`Across ${$} day${$===1?"":"s"} `:"",A=M>0?`you ran ${kn(M)} conversation${M===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let C=l.perAdapter.find(H=>H.isReal);R=`in ${C?rd(C.name):"Claude Code"}`}o.push(`${P}${A}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let M=Aq(),v=r?.cwd??process.cwd(),$=r?.now??Date.now(),P=r?.locale??M.locale,A=r?.tz??M.tz;return o.push(...Mq({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:v,locale:P,tz:A,now:$,version:e,latestVersion:n})),o.join(` -`)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),f=t.savings.total_bytes_returned,m=t.savings.total_calls,h=p+f,g=h>0?p/h*100:0,y=Math.round(p/4),_=f>0?Math.max(1,Math.round(h/Math.max(f,1))):0;if(p===0){o.push(`context-mode ${s} ${m} calls`),o.push(""),m===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${mt(f)} entered context | 0 tokens saved`),o.push(...vR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...TR(l)),o.push(...kR(i)),o.push(...wR(0,i)),o.push("");let M=e?`v${e}`:"context-mode";return o.push(M),e&&n&&n!=="unknown"&&$R(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(` -`)}o.push(`${kn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${od(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${Wr(h,h)}| ${mt(h)}`),o.push(`With context-mode |${Wr(f,h)}| ${mt(f)}`),o.push(""),_>=2?o.push(`${mt(p)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${mt(p)} kept out of your conversation. Never entered context.`),o.push("");let b=[`${m} calls`];t.cache&&t.cache.hits>0&&b.push(`${t.cache.hits} cache hits (+${mt(t.cache.bytes_saved)})`),o.push(b.join(" \xB7 "));let S=t.savings.by_tool.filter(M=>M.calls>0);if(S.length>=2){o.push("");let M=S.map(v=>{let $=v.context_kb*1024,P=g<100?$/(1-g/100):$,A=Math.max(0,P-$);return{...v,returnedBytes:$,estimatedSaved:A}}).sort((v,$)=>$.estimatedSaved-v.estimatedSaved);for(let v of M){let $=v.tool.length>22?v.tool.slice(0,19)+"...":v.tool;o.push(` ${$.padEnd(22)} ${String(v.calls).padStart(4)} calls ${mt(v.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let M=a.filter(v=>v.median_concurrency!=null&&(v.max_concurrency??1)>1);if(M.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 v of M){let $=v.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${$.padEnd(22)} ${v.calls} batches \xB7 ${v.median_concurrency} typical, ${v.max_concurrency} peak`)}}}o.push(...vR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...TR(l)),o.push(...kR(i)),o.push(...wR(y,i)),o.push("");let T=e?`v${e}`:"context-mode";return o.push(T),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(` -`)}var td,Eq,pi,Rq,CR,Oq,tQ,ER,OR=x(()=>{"use strict";hr();Jt();Sr();td={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"},Eq={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,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=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=n.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)}n.set(i,a)}let r=[];for(let[o,s]of n){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]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=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((C,H)=>C+H,0),s=Object.values(e.calls).reduce((C,H)=>C+H,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(C=>({tool:C,calls:e.calls[C]||0,context_kb:Math.round((e.bytesReturned[C]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[C]||0)/4)})),f=((Date.now()-e.sessionStart)/6e4).toFixed(1),m,h=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||h>0){let C=a+e.cacheBytesSaved,H=C/Math.max(o,1),W=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ge=e.cacheHits+h,Le=ge>0?e.cacheHits/ge:0;m={hits:e.cacheHits,misses:h,hit_rate:Le,bytes_saved:e.cacheBytesSaved,ttl_hours_left:W,total_with_cache:C,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,S=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),T=S?!S.consumed:!1,M=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),v=new Map;for(let C of M){v.has(C.category)||v.set(C.category,new Set);let H=v.get(C.category);if(H.size<5){let W=C.data;C.category==="file"?W=C.data.split("/").pop()||C.data:(C.category==="prompt"||C.category==="user-prompt")&&(W=W.length>50?W.slice(0,47)+"...":W),W.length>40&&(W=W.slice(0,37)+"..."),H.add(W)}}let $=y.map(C=>({category:C.category,count:C.cnt,label:td[C.category]||C.category,preview:v.get(C.category)?Array.from(v.get(C.category)).join(", "):"",why:Eq[C.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(C=>C.cnt>0).map(C=>({category:C.category,count:C.cnt,label:td[C.category]||C.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:m,session:{id:r,uptime_min:f},continuity:{total_events:g,by_category:$,compact_count:b,resume_ready:T},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:R}}}};Rq={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};CR={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},Oq={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};tQ=5/1e6;ER=256});var gC={};_e(gC,{AGY_DEFAULT_EXEC_TIMEOUT_MS:()=>cC,REGISTERED_CTX_TOOLS:()=>GR,__resetSuppressionDiagnosticForTests:()=>Yq,browserOpenArgv:()=>mC,buildBatchNodeOptionsPrefix:()=>iC,buildFetchCode:()=>pC,classifyIp:()=>oc,currentAttribution:()=>lr,emitSuppressionDiagnostic:()=>YR,extractSnippet:()=>yb,formatBatchQueryResults:()=>sC,getProjectDir:()=>Rt,installStrictClientSchemaCompat:()=>eC,killProcessOnPort:()=>hC,openBrowserSync:()=>fC,positionsFromHighlight:()=>oC,registerEmptyToolsListHandler:()=>QR,resolveExecTimeout:()=>vd,resolveSessionIdFromSessionDB:()=>tC,runBatchCommands:()=>lC,sanitizeSchemaForStrictClients:()=>gd,server:()=>Ce,shouldSuppressMcpToolsForNativePluginHost:()=>JR,withProjectDirOverride:()=>t4});import{createRequire as UR}from"node:module";import{existsSync as We,unlinkSync as gi,readdirSync as FR,readFileSync as sc,writeFileSync as fd,writeSync as Lq,renameSync as zq,rmSync as BR,mkdirSync as Hq,statSync as ZR,symlinkSync as Uq,lstatSync as qR,realpathSync as VR}from"node:fs";import{spawnSync as hd}from"node:child_process";import{join as zt,dirname as _i,resolve as Pt,sep as Fq,isAbsolute as Bq}from"node:path";import{fileURLToPath as Zq}from"node:url";import{homedir as yi,tmpdir as fb,cpus as qq}from"node:os";import{request as Vq}from"node:https";import{AsyncLocalStorage as Wq}from"node:async_hooks";function WR(){return We(Pt(dd,"package.json"))?dd:_i(dd)}function Kq(t){try{let e=process.platform==="win32"?hd("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):hd("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=Ac(String(e.stdout));if(n&&We(Pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function KR(t){let e=WR();return t==="codex"?Kq(e):e}function JR(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??Qe().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??Gq(n);return Jq(r)&&Xq(r)}function Gq(t){let e=t==="kilo"?"kilo":"opencode",n=[Pt(`${e}.json`),Pt(`${e}.jsonc`),Pt(`.${e}`,`${e}.json`),Pt(`.${e}`,`${e}.jsonc`),zt(yi(),".config",e,`${e}.json`),zt(yi(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!We(r))continue;return JSON.parse(Mi(sc(r,"utf8")))}catch{}return null}function Jq(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function Xq(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function YR(t={}){if(lb)return;lb=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=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 ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers). -`)}function Yq(){lb=!1}function QR(t=Ce){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(jo,async()=>({tools:[]}))}function e4(t,e){return async n=>{FP();try{return await e(n)}catch(r){let o=i4(r);if(o)try{return X(t,o)}catch(s){if(s instanceof Kt)return o;throw s}throw r}finally{BP()}}}async function t4(t,e){let n=typeof t=="string"?{projectDir:t}:t;return hb.run(n,e)}function gd(t){if(Array.isArray(t))return t.map(gd);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=gd(r)}return e}function eC(t=Ce){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(jo,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=gd(i.inputSchema)}catch{}}return s})}catch{}}function lr(){let t=hb.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??tC();if(e)return{sessionId:e}}function tC(t){let e=Date.now();if(!t?.bypassCache&&cd&&e-cd.checkedAt<2e3)return cd.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??Xe(),o=us({projectDir:n,sessionsDir:r});if(!We(o))return;let s=nt(),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&&(cd={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function n4(t){try{let e=Xe();if(!We(e))return;let n=FR(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=zt(e,r);try{t.index({path:o,source:"session-events",attribution:lr()}),gi(o)}catch{}}}catch{}}async function r4(){if(En)return En;try{let{getAdapter:t}=await Promise.resolve().then(()=>(uo(),dm)),e=Qe();return await t(e.platform)}catch{return null}}function mi(){if(En)return En.getSessionDir();try{let t=Qe(),e=Ui(t.platform);if(e)return $c({configDir:zt(...e),configDirEnv:o4(e)})}catch{}return $c({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function o4(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 br(_r(mi))}function Rt(){let t=hb.getStore();if(t)return t.projectDir;let e,n,r;try{let o=Qe().platform;n=o,o==="claude-code"&&(e=zt(yi(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??zt(yi(),".codex"))}catch{}return _R({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function s4(t){return Bq(t)?t:Pt(Rt(),t)}function fi(){return us({projectDir:Rt(),sessionsDir:Xe()})}function yd(){let t=br(Yr(mi));return rp({projectDir:Rt(),contentDir:t})}function Bn(){if(!wn){let t=yd();wn=new Ss(t),wn.setDenyChecker(e=>{try{let n=Rt(),r=po("Read",n);return Tr(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=_i(yd());_m(e,14),wn.cleanupStaleSources(14);let n=zt(yi(),".context-mode","content");We(n)&&_m(n,0)}catch{}ym()}return n4(wn),wn}function i4(t){return t instanceof Kt?{content:[{type:"text",text:cs(t)}],isError:!0}:null}async function AR(){return new Promise(t=>{let e=Vq("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function u4(){let t=En?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function l4(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function d4(){return!ur||ur==="unknown"?!1:l4(ur,cr)}function p4(){if(!d4())return!1;let t=Date.now();if(ud>=a4){if(t-IR0){let r=u4();e.content[0].text=`\u26A0\uFE0F context-mode v${cr} outdated \u2192 v${ur} available. Upgrade: ${r} + WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();h?.bytes&&(a+=Number(h.bytes))}catch{}}}finally{f.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=Qq(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 hb(t){let e=cd({worktreeHash:t.worktreeHash,sessionsDir:t.sessionsDir}),n=cd({sessionId:t.sessionId,worktreeHash:t.worktreeHash,sessionsDir:t.sessionsDir,contentDbPath:t.contentDbPath}),r=n.bytesReturned,o=e.bytesAvoided+e.bytesReturned,s=Math.max(0,o-r);return{eventDataBytes:e.eventDataBytes,bytesAvoided:s,bytesReturned:r,snapshotBytes:e.snapshotBytes,contentBytes:n.contentBytes,totalSavedTokens:Math.floor((e.eventDataBytes+s+e.snapshotBytes)/4)}}function t4(t,e,n){let r={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(!ar(t.sessionsDir))return r;let o=[];try{o=mi(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=Vt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let f=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(r.eventCount+=Number(f.cnt??0),r.dataBytes+=Number(f.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.sessionCount+=Number(m?.cnt??0)}catch{}try{let m=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();m?.bytes&&(r.rescueBytes+=Number(m.bytes))}catch{}try{let m=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(m?.mn){let h=Date.parse(m.mn+(m.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&hr.lastMs&&(r.lastMs=h)}}catch{}try{let m=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of m)h.p&&i.add(h.p)}catch{}try{let m=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of m)h.s&&a.add(h.s)}catch{}}finally{p.close()}}catch{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function pd(t){let e=Xq({home:t?.home}),n=t?.loadDatabase??ot,r={...e4,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!ar(c.sessionsDir))continue;let u=t4(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function ud(t){return n4[t]??t}function ft(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 n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function r4(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function id(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function o4(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!id(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=Wq("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!id(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!id(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return id(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function jR(t){let e=dd();return e?t===e?"~":t.startsWith(e+Gq)?"~"+t.slice(e.length):t:t}function s4(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*sc(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),f=(e*1/1e6).toFixed(2),m=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,h=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return m&&h?g.push(` $${o(r)} of ${h} tokens your team didn't burn.`):m?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${ft(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.`)),m||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function i4(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*FR,f=Math.round((e.snapshotBytes??0)/4),m=p+f,h=o?.conversation?.totalSavedTokens??0,g=Math.max(m,h),y=(n?.totalEvents??0)*FR,_=Math.round((n?.rescueBytes??0)/4),b=y+_,v=o?.lifetime?.totalSavedTokens??0,T=Math.max(b,v),M=o?.lifetime?.bytesReturned??0,S=o?.lifetime?.bytesAvoided??0,$=M+S>0?Math.max(1,Math.floor(M/4)):Math.max(1,Math.round(T*.02)),P=r?.totalBytes&&r.totalBytes>0?r.totalBytes:T*4,A=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`,C=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=C>0?Math.max(1,Math.round((c-C)/864e5)):0,W=r?.totalSessions??n?.totalSessions??1,ge=r?.perAdapter.filter(Fe=>Fe.isReal).length??0,ze;if(r&&ge>=2)ze=`across ${ge} AI tools`;else if(r&&ge===1){let Fe=r.perAdapter.find(dn=>dn.isReal);ze=`in ${Fe?ud(Fe.name):"Claude Code"}`}else ze="in Claude Code";H>0?d.push(` Across ${H} days you ran ${Sn(W)} conversations ${ze}.`):d.push(` You ran ${Sn(W)} conversations ${ze}.`);let at=H>0?P/H:0;d.push(` context-mode kept ${ft(P)} out of your context window \u2014 about ${ft(at)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Tn=e.firstEventMs&&e.firstEventMs>0?LR(e.firstEventMs,i,a):"";if(Tn?d.push(` This conversation started ${Tn} in ${jR(s)}.`):d.push(` This conversation lives in ${jR(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Fe=e.lastRescueMs&&e.lastRescueMs>0?LR(e.lastRescueMs,i,a):"",dn=Math.round(e.snapshotBytes/1024);Fe?d.push(` On ${Fe}, /compact fired \u2014 ${dn} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${dn} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let fc=o?.conversation,hc=fc?.bytesAvoided??0,jd=fc?.bytesReturned??0;if(hc+jd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Fe=hc+jd,dn=Math.max(1,jd),pn=Math.max(1,Math.floor(Fe/4)),Vn=Math.max(1,Math.floor(dn/4)),Ld=Wr(pn,pn,32),fO=Wr(Vn,pn,32),hO=(1-Vn/pn)*100,gO=Math.max(1,Math.round(pn/Vn));d.push(` Without context-mode ${ft(Fe).padStart(8)} ${Ld} ${Sn(pn).padStart(7)} tokens`),d.push(` With context-mode ${ft(dn).padStart(8)} ${fO} ${Sn(Vn).padStart(7)} tokens`),d.push(` ${hO.toFixed(1)}% kept out of context \xB7 your AI ran ${gO}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Fe=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${ft(A)} built up \u2014 ${Fe} days, ${e.byDay.length} active:`),d.push(""),d.push(...c4(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 lO=e.byCategory.reduce((Fe,dn)=>Fe+dn.count,0).toLocaleString(i);d.push(` ${lO} things \u2014 files, errors, decisions, agent runs:`),d.push("");let dO=e.byCategory[0]?.count??1;for(let Fe of e.byCategory)d.push(` ${Fe.label.padEnd(26)} ${String(Fe.count).padStart(5)} ${Wr(Fe.count,dO,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let jb=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Lb=C>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(C)):"",zb=n?.distinctProjects??0,pO=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${ft(A)} kept out \xB7 ${e.events.toLocaleString(i)} captures${jb?` \xB7 started ${jb}`:""}.`),d.push(` All your work: ${ft(P)} kept out \xB7 ${pO.toLocaleString(i)} captures across ${zb} project${zb===1?"":"s"}${Lb?` \xB7 since ${Lb}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...s4(P,T,H)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Fe=Object.entries(n.autoMemoryByPrefix).sort((pn,Vn)=>Vn[1]-pn[1]),dn=Fe.length>0?Fe[0][1]:1;for(let[pn,Vn]of Fe){let Ld=WR[pn]??pn;d.push(` ${Ld.padEnd(26)} ${String(Vn).padStart(2)} ${Wr(Vn,dn,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 mO=u?`v${u}`:"context-mode";return d.push(` ${mO}`),u&&l&&l!=="unknown"&&ZR(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),a4(d)}function a4(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function c4(t,e,n){if(t.length===0)return[];let r=[...t].sort((p,f)=>p.ms-f.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let p of r)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of r){let f=Math.round((p.ms-o.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[f]=m}let l=p=>{let f=new Intl.DateTimeFormat(e,{timeZone:n,month:"short",day:"numeric"}).formatToParts(new Date(p)),m=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${m} ${h}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of r){let f=l(p.ms).padEnd(7),m=`${p.count} captures`,h=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${f} ${m}${h}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function LR(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),s=d=>o.find(p=>p.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} (${n})`}function Sn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function sc(){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 5/1e6}function ld(t){return`$${((Number.isFinite(t)&&t>0?t:0)*sc()).toFixed(2)}`}function Wr(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function zR(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=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 ${Sn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${Sn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&n>0?1:c,g=h===1?"1 session":`${Sn(h)} sessions`,y=a*256+n;o.push(` ${Sn(a)} events \xB7 ${g} \xB7 ~${ld(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:ad[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let p=d.slice(0,r),f=p.length>0?p[0].count:1;for(let h of p)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${Wr(h.count,f,30)}`);let m=Math.max(0,d.length-r);return m>0&&o.push(` ... ${m} more categor${m===1?"y":"ies"}`),o}function HR(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 n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=WR[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Wr(s,r,20)}`)}return e}function UR(t,e){let n=[],r=ld(t),o=(e?.totalEvents??0)*256+t,s=ld(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}function BR(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.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?Sn(u.eventCount):"\u2014",p=ft(u.dataBytes),f=ft(l);r.push(` ${ud(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${f.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>ud(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function md(t,e,n,r){let o=[],s=r4(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(M=>M.isReal).length??0;if(l&&d>0){let M=l.totalSessions||i?.totalSessions||0,S=i?.firstEventMs??0,$=S>0?Math.max(1,Math.round((Date.now()-S)/864e5)):0,P=$>0?`Across ${$} day${$===1?"":"s"} `:"",A=M>0?`you ran ${Sn(M)} conversation${M===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let C=l.perAdapter.find(H=>H.isReal);R=`in ${C?ud(C.name):"Claude Code"}`}o.push(`${P}${A}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let M=o4(),S=r?.cwd??process.cwd(),$=r?.now??Date.now(),P=r?.locale??M.locale,A=r?.tz??M.tz;return o.push(...i4({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:S,locale:P,tz:A,now:$,version:e,latestVersion:n})),o.join(` +`)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),f=t.savings.total_bytes_returned,m=t.savings.total_calls,h=p+f,g=h>0?p/h*100:0,y=Math.round(p/4),_=f>0?Math.max(1,Math.round(h/Math.max(f,1))):0;if(p===0){o.push(`context-mode ${s} ${m} calls`),o.push(""),m===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${ft(f)} entered context | 0 tokens saved`),o.push(...zR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...BR(l)),o.push(...HR(i)),o.push(...UR(0,i)),o.push("");let M=e?`v${e}`:"context-mode";return o.push(M),e&&n&&n!=="unknown"&&ZR(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(` +`)}o.push(`${Sn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${ld(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${Wr(h,h)}| ${ft(h)}`),o.push(`With context-mode |${Wr(f,h)}| ${ft(f)}`),o.push(""),_>=2?o.push(`${ft(p)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${ft(p)} kept out of your conversation. Never entered context.`),o.push("");let b=[`${m} calls`];t.cache&&t.cache.hits>0&&b.push(`${t.cache.hits} cache hits (+${ft(t.cache.bytes_saved)})`),o.push(b.join(" \xB7 "));let v=t.savings.by_tool.filter(M=>M.calls>0);if(v.length>=2){o.push("");let M=v.map(S=>{let $=S.context_kb*1024,P=g<100?$/(1-g/100):$,A=Math.max(0,P-$);return{...S,returnedBytes:$,estimatedSaved:A}}).sort((S,$)=>$.estimatedSaved-S.estimatedSaved);for(let S of M){let $=S.tool.length>22?S.tool.slice(0,19)+"...":S.tool;o.push(` ${$.padEnd(22)} ${String(S.calls).padStart(4)} calls ${ft(S.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let M=a.filter(S=>S.median_concurrency!=null&&(S.max_concurrency??1)>1);if(M.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 S of M){let $=S.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${$.padEnd(22)} ${S.calls} batches \xB7 ${S.median_concurrency} typical, ${S.max_concurrency} peak`)}}}o.push(...zR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...BR(l)),o.push(...HR(i)),o.push(...UR(y,i)),o.push("");let T=e?`v${e}`:"context-mode";return o.push(T),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(` +`)}var ad,Jq,fi,e4,WR,n4,UQ,FR,KR=x(()=>{"use strict";hr();Ut();vr();ad={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"},Jq={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"},fi=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=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=n.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)}n.set(i,a)}let r=[];for(let[o,s]of n){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]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=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((C,H)=>C+H,0),s=Object.values(e.calls).reduce((C,H)=>C+H,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(C=>({tool:C,calls:e.calls[C]||0,context_kb:Math.round((e.bytesReturned[C]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[C]||0)/4)})),f=((Date.now()-e.sessionStart)/6e4).toFixed(1),m,h=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||h>0){let C=a+e.cacheBytesSaved,H=C/Math.max(o,1),W=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ge=e.cacheHits+h,ze=ge>0?e.cacheHits/ge:0;m={hits:e.cacheHits,misses:h,hit_rate:ze,bytes_saved:e.cacheBytesSaved,ttl_hours_left:W,total_with_cache:C,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.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(r),T=v?!v.consumed:!1,M=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),S=new Map;for(let C of M){S.has(C.category)||S.set(C.category,new Set);let H=S.get(C.category);if(H.size<5){let W=C.data;C.category==="file"?W=C.data.split("/").pop()||C.data:(C.category==="prompt"||C.category==="user-prompt")&&(W=W.length>50?W.slice(0,47)+"...":W),W.length>40&&(W=W.slice(0,37)+"..."),H.add(W)}}let $=y.map(C=>({category:C.category,count:C.cnt,label:ad[C.category]||C.category,preview:S.get(C.category)?Array.from(S.get(C.category)).join(", "):"",why:Jq[C.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(C=>C.cnt>0).map(C=>({category:C.category,count:C.cnt,label:ad[C.category]||C.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:m,session:{id:r,uptime_min:f},continuity:{total_events:g,by_category:$,compact_count:b,resume_ready:T},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:R}}}};e4={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};WR={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},n4={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};UQ=5/1e6;FR=256});var AC={};ye(AC,{AGY_DEFAULT_EXEC_TIMEOUT_MS:()=>EC,REGISTERED_CTX_TOOLS:()=>pC,__resetSuppressionDiagnosticForTests:()=>k4,browserOpenArgv:()=>CC,buildBatchNodeOptionsPrefix:()=>kC,buildFetchCode:()=>RC,classifyIp:()=>ac,currentAttribution:()=>lr,emitSuppressionDiagnostic:()=>hC,extractSnippet:()=>$b,formatBatchQueryResults:()=>SC,getProjectDir:()=>Rt,installStrictClientSchemaCompat:()=>yC,killProcessOnPort:()=>IC,openBrowserSync:()=>OC,positionsFromHighlight:()=>vC,registerEmptyToolsListHandler:()=>gC,resolveExecTimeout:()=>Pd,resolveSessionIdFromSessionDB:()=>_C,runBatchCommands:()=>$C,sanitizeSchemaForStrictClients:()=>Sd,server:()=>Ce,shouldSuppressMcpToolsForNativePluginHost:()=>mC,withProjectDirOverride:()=>T4});import{createRequire as oC}from"node:module";import{existsSync as We,unlinkSync as _i,readdirSync as sC,readFileSync as cc,writeFileSync as xd,writeSync as u4,renameSync as l4,rmSync as iC,mkdirSync as d4,statSync as aC,symlinkSync as p4,lstatSync as cC,realpathSync as uC}from"node:fs";import{spawnSync as vd}from"node:child_process";import{join as zt,dirname as xi,resolve as Pt,sep as m4,isAbsolute as f4}from"node:path";import{fileURLToPath as h4}from"node:url";import{homedir as bi,tmpdir as wb,cpus as g4}from"node:os";import{request as y4}from"node:https";import{AsyncLocalStorage as _4}from"node:async_hooks";function lC(){return We(Pt(yd,"package.json"))?yd:xi(yd)}function b4(t){try{let e=process.platform==="win32"?vd("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):vd("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=Dc(String(e.stdout));if(n&&We(Pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function dC(t){let e=lC();return t==="codex"?b4(e):e}function mC(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??tt().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??x4(n);return v4(r)&&S4(r)}function x4(t){let e=t==="kilo"?"kilo":"opencode",n=[Pt(`${e}.json`),Pt(`${e}.jsonc`),Pt(`.${e}`,`${e}.json`),Pt(`.${e}`,`${e}.jsonc`),zt(bi(),".config",e,`${e}.json`),zt(bi(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!We(r))continue;return JSON.parse(ji(cc(r,"utf8")))}catch{}return null}function v4(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function S4(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function hC(t={}){if(xb)return;xb=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=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 ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers). +`)}function k4(){xb=!1}function gC(t=Ce){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(zo,async()=>({tools:[]}))}function E4(t,e){return async n=>{sR();try{return await e(n)}catch(r){let o=O4(r);if(o)try{return X(t,o)}catch(s){if(s instanceof Gt)return o;throw s}throw r}finally{iR()}}}async function T4(t,e){let n=typeof t=="string"?{projectDir:t}:t;return Eb.run(n,e)}function Sd(t){if(Array.isArray(t))return t.map(Sd);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=Sd(r)}return e}function yC(t=Ce){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(zo,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=Sd(i.inputSchema)}catch{}}return s})}catch{}}function lr(){let t=Eb.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??_C();if(e)return{sessionId:e}}function _C(t){let e=Date.now();if(!t?.bypassCache&&fd&&e-fd.checkedAt<2e3)return fd.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??Qe(),o=ds({projectDir:n,sessionsDir:r});if(!We(o))return;let s=ot(),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&&(fd={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function $4(t){try{let e=Qe();if(!We(e))return;let n=sC(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=zt(e,r);try{t.index({path:o,source:"session-events",attribution:lr()}),_i(o)}catch{}}}catch{}}async function P4(){if(wn)return wn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(po(),vm)),e=tt();return await t(e.platform)}catch{return null}}function hi(){if(wn)return wn.getSessionDir();try{let t=tt(),e=Zi(t.platform);if(e)return Cc({configDir:zt(...e),configDirEnv:R4(e)})}catch{}return Cc({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function R4(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Qe(){return br(_r(hi))}function Rt(){let t=Eb.getStore();if(t)return t.projectDir;let e,n,r;try{let o=tt().platform;n=o,o==="claude-code"&&(e=zt(bi(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??zt(bi(),".codex"))}catch{}return MR({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function C4(t){return f4(t)?t:Pt(Rt(),t)}function gi(){return ds({projectDir:Rt(),sessionsDir:Qe()})}function kd(){let t=br(Yr(hi));return up({projectDir:Rt(),contentDir:t})}function Bn(){if(!kn){let t=kd();kn=new ks(t),kn.setDenyChecker(e=>{try{let n=Rt(),r=fo("Read",n);return Tr(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=xi(kd());Pm(e,14),kn.cleanupStaleSources(14);let n=zt(bi(),".context-mode","content");We(n)&&Pm(n,0)}catch{}$m()}return $4(kn),kn}function O4(t){return t instanceof Gt?{content:[{type:"text",text:ls(t)}],isError:!0}:null}async function JR(){return new Promise(t=>{let e=y4("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function N4(){let t=wn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function M4(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function D4(){return!ur||ur==="unknown"?!1:M4(ur,cr)}function j4(){if(!D4())return!1;let t=Date.now();if(hd>=I4){if(t-GR0){let r=N4();e.content[0].text=`\u26A0\uFE0F context-mode v${cr} outdated \u2192 v${ur} available. Upgrade: ${r} -`+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+n,_d(),setImmediate(()=>nR(fi(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>XP({sessionDbPath:fi(),toolName:t,bytesReturned:n})),(t==="ctx_search"||t==="ctx_fetch_and_index")&&setImmediate(()=>sR(fi(),n)),e}function Tn(t,e="unknown"){ie.bytesIndexed+=t,_d(),t>0&&setImmediate(()=>YP({sessionDbPath:fi(),source:e,bytesAvoided:t}))}function b4(t){return _4.test(t)?t:`pid-${process.ppid}`}function nC(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=b4(t),n=br(as(mi));return zt(n,`stats-${e}.json`)}function _d(){let t=Date.now();if(!(t-dbd+p,0),n=Object.values(ie.calls).reduce((d,p)=>d+p,0),r=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=ld?.tokens??0;if(!ld||t-ld.computedAt>g4)try{a=(tc({sessionsDir:Xe()})?.totalEvents??0)*y4,ld={tokens:a,computedAt:t}}catch{}let c={schemaVersion:h4,version:cr,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*nc()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*nc()).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=nC(),l=`${u}.tmp`;fd(l,JSON.stringify(c)),zq(l,u)}catch{}}}function gb(t,e){try{let n=vm(process.env.CLAUDE_PROJECT_DIR),r=wm(t,n);if(r.decision==="deny")return X(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function rC(t,e,n){try{let r=Bv(t,e);if(r.length===0)return null;let o=vm(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=wm(s,o);if(i.decision==="deny")return X(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function x4(t,e){try{let n=Rt(),r=km("Read","allow",n);return Fv(t,n,r).allowed?null:X(e,{content:[{type:"text",text:`File access blocked: "${t}" resolves outside the project root (${n}). context-mode confines ${e} to the workspace so it cannot be used to bypass the host's sandbox/permission controls (issue #852). To intentionally process a file outside the project, add a host allow rule, e.g. "permissions": { "allow": ["Read(${t})"] } in your settings.`}],isError:!0})}catch{}return null}function pb(t,e){try{let n=Rt(),r=po("Read",n),o=Tr(t,r,process.platform==="win32",n);if(o.denied)return X(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function oC(t){let e=[],n=0,r=0;for(;rd.length>2),l=t.toLowerCase();for(let d of u){let p=l.indexOf(d);for(;p!==-1;)o.push(p),p=l.indexOf(d,p+1)}}if(o.length===0)return t.slice(0,n)+` +`+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+n,wd(),setImmediate(()=>bR(gi(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>fR({sessionDbPath:gi(),toolName:t,bytesReturned:n})),(t==="ctx_search"||t==="ctx_fetch_and_index")&&setImmediate(()=>SR(gi(),n)),e}function En(t,e="unknown"){ie.bytesIndexed+=t,wd(),t>0&&setImmediate(()=>hR({sessionDbPath:gi(),source:e,bytesAvoided:t}))}function Z4(t){return B4.test(t)?t:`pid-${process.ppid}`}function bC(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=Z4(t),n=br(us(hi));return zt(n,`stats-${e}.json`)}function wd(){let t=Date.now();if(!(t-vbd+p,0),n=Object.values(ie.calls).reduce((d,p)=>d+p,0),r=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=gd?.tokens??0;if(!gd||t-gd.computedAt>U4)try{a=(oc({sessionsDir:Qe()})?.totalEvents??0)*F4,gd={tokens:a,computedAt:t}}catch{}let c={schemaVersion:H4,version:cr,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*sc()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*sc()).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=bC(),l=`${u}.tmp`;xd(l,JSON.stringify(c)),l4(l,u)}catch{}}}function Tb(t,e){try{let n=Im(process.env.CLAUDE_PROJECT_DIR),r=Nm(t,n);if(r.decision==="deny")return X(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function xC(t,e,n){try{let r=ak(t,e);if(r.length===0)return null;let o=Im(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=Nm(s,o);if(i.decision==="deny")return X(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function q4(t,e){try{let n=Rt(),r=Am("Read","allow",n);return ik(t,n,r).allowed?null:X(e,{content:[{type:"text",text:`File access blocked: "${t}" resolves outside the project root (${n}). context-mode confines ${e} to the workspace so it cannot be used to bypass the host's sandbox/permission controls (issue #852). To intentionally process a file outside the project, add a host allow rule, e.g. "permissions": { "allow": ["Read(${t})"] } in your settings.`}],isError:!0})}catch{}return null}function Sb(t,e){try{let n=Rt(),r=fo("Read",n),o=Tr(t,r,process.platform==="win32",n);if(o.denied)return X(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function vC(t){let e=[],n=0,r=0;for(;rd.length>2),l=t.toLowerCase();for(let d of u){let p=l.indexOf(d);for(;p!==-1;)o.push(p),p=l.indexOf(d,p+1)}}if(o.length===0)return t.slice(0,n)+` \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>=n)break;let d=t.slice(u,Math.min(l,u+(n-c)));a.push((u>0?"\u2026":"")+d+(lr){s.push(`## ${c} +`)}function SC(t,e,n,r=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:n;for(let c of e){if(i>r){s.push(`## ${c} (output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details) -`);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=yb(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(` -> **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 E4(t){return`'${t.replace(/'/g,"'\\''")}'`}function T4(t){return`'${t.replace(/'/g,"''")}'`}function iC(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${T4(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${E4(n)} `}function aC(t){let e=t.replace(/\s+/g," ").trim();return e.length<=MR?e:e.slice(0,MR)+"\u2026"}function vd(t){if(t!==void 0)return t;if(Qe().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:cC}function $4(t){return t.length<=DR?t:t.slice(0,DR)+` -\u2026 (truncated)`}function uC(t,e,n){let r=n?`path=${n} +`);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=$b(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(` +> **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 J4(t){return`'${t.replace(/'/g,"'\\''")}'`}function X4(t){return`'${t.replace(/'/g,"''")}'`}function kC(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${X4(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${J4(n)} `}function wC(t){let e=t.replace(/\s+/g," ").trim();return e.length<=YR?e:e.slice(0,YR)+"\u2026"}function Pd(t){if(t!==void 0)return t;if(tt().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:EC}function Y4(t){return t.length<=QR?t:t.slice(0,QR)+` +\u2026 (truncated)`}function TC(t,e,n){let r=n?`path=${n} `:"",o=`\`\`\`${t} -${$4(e)} +${Y4(e)} \`\`\``;return`${r}${o} -`}function jR(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=aC(e);return`# ${t} +`}function eC(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=wC(e);return`# ${t} $ ${a} ${o} -`}function LR(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(` +`}function tC(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(` `)?"":` -`}${n}`:n:e}async function lC(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let p=[],f=Date.now(),m=!1;for(let h=0;h({run:async()=>{let f=await n.execute({language:"shell",code:`${s}${p.command}`,timeout:r,cwd:i}),m=jR(p.label,p.command,LR(f),a);return{output:f.timedOut?m.replace(/\n$/,"")+` +`);break}}return{outputs:p,timedOut:m}}let c=t.map(p=>({run:async()=>{let f=await n.execute({language:"shell",code:`${s}${p.command}`,timeout:r,cwd:i}),m=eC(p.label,p.command,tC(f),a);return{output:f.timedOut?m.replace(/\n$/,"")+` (timed out after ${r??"?"}ms) -`:m,timedOut:!!f.timedOut}}})),{settled:u}=await J_(c,{concurrency:o}),l=new Array(t.length),d=!1;for(let p=0;p0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(` `)}let l=[`Indexed ${a.totalChunks} sections from "${n}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let p=d.content.split(` `)[0].slice(0,120);l.push(` - ${d.title}: ${p}`)}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(` -`)}function _b(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}function C4(){try{return lr()?.sessionId??"__default__"}catch{return"__default__"}}function bb(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function xb(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function O4(t){let e=bb(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}function I4(){return ib||(ib=UR(import.meta.url).resolve("turndown")),ib}function A4(){return ab||(ab=UR(import.meta.url).resolve("turndown-plugin-gfm")),ab}function pC(t,e){let n=JSON.stringify(I4()),r=JSON.stringify(A4()),o=JSON.stringify(e),s=oc.toString(),i=oc.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s}; +`)}function Pb(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}function tV(){try{return lr()?.sessionId??"__default__"}catch{return"__default__"}}function Rb(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function Cb(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function nV(t){let e=Rb(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}function rV(){return gb||(gb=oC(import.meta.url).resolve("turndown")),gb}function oV(){return yb||(yb=oC(import.meta.url).resolve("turndown-plugin-gfm")),yb}function RC(t,e){let n=JSON.stringify(rV()),r=JSON.stringify(oV()),o=JSON.stringify(e),s=ac.toString(),i=ac.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s}; var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return` const TurndownService = require(${n}); const { gfm } = require(${r}); @@ -905,14 +910,14 @@ async function main() { emit('text', text); } main(); -`}function M4(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}async function D4(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 n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=oc(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"&&n)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(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),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 oc(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?oc(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.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 j4(t,e,n,r){let o=await D4(t);if(o)return o;if(!n&&r!==0){let i=Bn(),a=X_(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??N4;if(l0?`${p}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:m,ttlStr:M4(d)}}}}let s=zt(fb(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=pC(t,s),a=await ic.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",p=/\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}${p}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=ZR(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=sc(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{BR(s)}catch{}}}function L4(t){let e=Bn(),n=X_(t.source,t.url),r=lr(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,n,void 0,r):o=e.index({content:t.markdown,source:n,attribution:r}),Tn(Buffer.byteLength(t.markdown));let s=t.markdown.length>zR?WP(t.markdown,zR)+` +`}function iV(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}async function aV(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 n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=ac(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"&&n)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(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),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 ac(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?ac(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.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 cV(t,e,n,r){let o=await aV(t);if(o)return o;if(!n&&r!==0){let i=Bn(),a=ab(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??sV;if(l0?`${p}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:m,ttlStr:iV(d)}}}}let s=zt(wb(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=RC(t,s),a=await uc.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",p=/\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}${p}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=aC(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=cc(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{iC(s)}catch{}}}function uV(t){let e=Bn(),n=ab(t.source,t.url),r=lr(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,n,void 0,r):o=e.index({content:t.markdown,source:n,attribution:r}),En(Buffer.byteLength(t.markdown));let s=t.markdown.length>nC?lR(t.markdown,nC)+` -\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 cb(t,e){if(!We(e))return;let n=0;try{for(let r of FR(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(sc(zt(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function HR(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function mC(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 fC(t,e=process.platform,n=hd){let r=mC(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:rc});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 hC(t,e=process.platform,n=hd){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:rc});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;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],p=u[2],f=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:rc});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:rc});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:rc});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}async function z4(){let t=ym();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?fb():"/tmp",n=zt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{ic.cleanupBackgrounded(),wn&&wn.close();try{gi(Sd)}catch{}try{gi(n)}catch{}r&&clearInterval(r)},s=async()=>{try{db=0,_d()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),qP({onShutdown:()=>s()});let i=new Wl;await Ce.connect(i),ZP(i);try{fd(n,String(process.pid))}catch{}r=setInterval(()=>{try{fd(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(uo(),dm)),u=Ce.server.getClientVersion(),l=a(u??void 0);En=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=rR(fi());if(a){for(let[c,u]of Object.entries(a.calls))ie.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ie.bytesReturned[c]=u;a.sessionStart>0&&(ie.sessionStart=a.sessionStart)}}catch{}AR().then(a=>{a!=="unknown"&&(ur=a)}),setInterval(()=>{AR().then(a=>{a!=="unknown"&&(ur=a)})},3600*1e3).unref(),setInterval(()=>_d(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${cr} running on stdio`),console.error(`Detected runtimes: -${Ti(Jo)}`),mr()||(console.error(` -Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var dd,cr,Jo,pd,Ce,GR,XR,lb,Qq,hb,ic,Sd,wn,cd,En,ie,ur,ud,IR,a4,c4,NR,f4,h4,g4,y4,db,ld,_4,S4,v4,k4,w4,MR,cC,DR,bd,xd,P4,mb,md,R4,ib,ab,N4,zR,rc,ub,yC=x(()=>{"use strict";vP();TP();Zl();G_();zP();bm();HP();Em();Yo();UP();VP();KP();Jt();JP();eR();oR();iR();pR();hR();gR();Rn();uo();$p();Yd();Di();Sr();bR();hr();OR();Lo();dd=_i(Zq(import.meta.url)),cr=(()=>{for(let t of["../package.json","./package.json"]){let e=Pt(dd,t);if(We(e))try{return JSON.parse(sc(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} -`)}),process.on("uncaughtException",t=>{try{Lq(2,`[context-mode] uncaughtException: ${t?.message??t} -`)}finally{process.exit(1)}}));Jo=Xr(),pd=$i(Jo),Ce=new ql({name:"context-mode",version:cr}),GR=[];XR=JR(),lb=!1;Qq=Ce.registerTool.bind(Ce);Ce.registerTool=(...t)=>{let[e,n,r]=t;if(XR){YR();return}let o=e4(e,r);return GR.push({name:e,config:n,handler:o}),t[2]=o,Qq(...t)};XR&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&QR(Ce);hb=new Wq;Ce.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ce.server.setRequestHandler(Us,async()=>({prompts:[]}));Ce.server.setRequestHandler(zs,async()=>({resources:[]}));Ce.server.setRequestHandler(Hs,async()=>({resourceTemplates:[]}));ic=new ci({runtimes:Jo,projectRoot:()=>Rt()}),Sd=zt(fb(),`cm-fs-preload-${process.pid}.js`);fd(Sd,`(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){}})(); -`);process.on("exit",()=>{try{gi(Sd)}catch{}});wn=null;En=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};ur=null,ud=0,IR=0,a4=3,c4=3600*1e3;NR=!1;f4=500,h4=2,g4=3e4,y4=256,db=0,_4=/^[A-Za-z0-9._-]+$/;S4=pd.join(", "),v4=mr()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",k4="",w4="";MR=500;cC=12e4;DR=2e3;Ce.registerTool("ctx_execute",{title:"Run code in a sandbox (executes the supplied code)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${v4} Languages: ${S4}. +\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 _b(t,e){if(!We(e))return;let n=0;try{for(let r of sC(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(cc(zt(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function rC(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function CC(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 OC(t,e=process.platform,n=vd){let r=CC(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:ic});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 IC(t,e=process.platform,n=vd){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ic});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;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],p=u[2],f=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:ic});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ic});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:ic});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}async function lV(){let t=$m();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?wb():"/tmp",n=zt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{uc.cleanupBackgrounded(),kn&&kn.close();try{_i($d)}catch{}try{_i(n)}catch{}r&&clearInterval(r)},s=async()=>{try{vb=0,wd()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),cR({onShutdown:()=>s()});let i=new Ql;await Ce.connect(i),aR(i);try{xd(n,String(process.pid))}catch{}r=setInterval(()=>{try{xd(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(po(),vm)),u=Ce.server.getClientVersion(),l=a(u??void 0);wn=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=xR(gi());if(a){for(let[c,u]of Object.entries(a.calls))ie.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ie.bytesReturned[c]=u;a.sessionStart>0&&(ie.sessionStart=a.sessionStart)}}catch{}JR().then(a=>{a!=="unknown"&&(ur=a)}),setInterval(()=>{JR().then(a=>{a!=="unknown"&&(ur=a)})},3600*1e3).unref(),setInterval(()=>wd(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${cr} running on stdio`),console.error(`Detected runtimes: +${Pi(Yo)}`),mr()||(console.error(` +Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var yd,cr,Yo,_d,Ce,pC,fC,xb,w4,Eb,uc,$d,kn,fd,wn,ie,ur,hd,GR,I4,A4,XR,z4,H4,U4,F4,vb,gd,B4,V4,W4,K4,G4,YR,EC,QR,Ed,Td,Q4,kb,bd,eV,gb,yb,sV,nC,ic,bb,NC=x(()=>{"use strict";zP();BP();Jl();sb();nR();Rm();rR();Mm();es();oR();uR();dR();Ut();mR();yR();vR();kR();RR();IR();AR();Pn();po();Ap();op();Li();vr();DR();hr();KR();Ho();yd=xi(h4(import.meta.url)),cr=(()=>{for(let t of["../package.json","./package.json"]){let e=Pt(yd,t);if(We(e))try{return JSON.parse(cc(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} +`)}),process.on("uncaughtException",t=>{try{u4(2,`[context-mode] uncaughtException: ${t?.message??t} +`)}finally{process.exit(1)}}));Yo=Xr(),_d=Ri(Yo),Ce=new Xl({name:"context-mode",version:cr}),pC=[];fC=mC(),xb=!1;w4=Ce.registerTool.bind(Ce);Ce.registerTool=(...t)=>{let[e,n,r]=t;if(fC){hC();return}let o=E4(e,r);return pC.push({name:e,config:n,handler:o}),t[2]=o,w4(...t)};fC&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&gC(Ce);Eb=new _4;Ce.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ce.server.setRequestHandler(Zs,async()=>({prompts:[]}));Ce.server.setRequestHandler(Fs,async()=>({resources:[]}));Ce.server.setRequestHandler(Bs,async()=>({resourceTemplates:[]}));uc=new li({runtimes:Yo,projectRoot:()=>Rt()}),$d=zt(wb(),`cm-fs-preload-${process.pid}.js`);xd($d,`(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){}})(); +`);process.on("exit",()=>{try{_i($d)}catch{}});kn=null;wn=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};ur=null,hd=0,GR=0,I4=3,A4=3600*1e3;XR=!1;z4=500,H4=2,U4=3e4,F4=256,vb=0,B4=/^[A-Za-z0-9._-]+$/;V4=_d.join(", "),W4=mr()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",K4="",G4="";YR=500;EC=12e4;QR=2e3;Ce.registerTool("ctx_execute",{title:"Run code in a sandbox (executes the supplied code)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${W4} Languages: ${V4}. 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. @@ -943,9 +948,9 @@ RETURNS: 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. EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('npm test', {encoding:'utf8', stdio:['ignore','pipe','pipe']}); console.log(out.split('\\\\n').filter(l => /(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))/i.test(l)).slice(0, 60).join('\\\\n'))") -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:j.object({language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.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:j.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:j.preprocess(xb,j.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."),cwd:j.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),intent:j.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'. +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:j.object({language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.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:j.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:j.preprocess(Cb,j.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."),cwd:j.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),intent:j.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'. -TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=gb(e,"execute");if(i)return i}else{let i=rC(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=` +TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=Tb(e,"execute");if(i)return i}else{let i=xC(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=` // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile let __cm_fs=0; process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}}); @@ -1004,14 +1009,14 @@ ${e} } __cm_main().catch(e=>{console.error(e);process.exitCode=1});${r?` setInterval(()=>{},2147483647);`:""} -})(typeof require!=='undefined'?require:null);`);let a=vd(n),c=await ic.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=uC(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ie.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ie.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let f=c.stdout?.trim();return c.backgrounded&&f?X("ctx_execute",{content:[{type:"text",text:`${u}${f} +})(typeof require!=='undefined'?require:null);`);let a=Pd(n),c=await uc.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=TC(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ie.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ie.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let f=c.stdout?.trim();return c.backgrounded&&f?X("ctx_execute",{content:[{type:"text",text:`${u}${f} _(process backgrounded after ${a}ms \u2014 still running)_`}]}):f?X("ctx_execute",{content:[{type:"text",text:`${u}${f} _(timed out after ${a}ms \u2014 partial output shown above)_`}]}):X("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms stderr: -${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:f,output:m}=Y_({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(m)>bd?(Tn(Buffer.byteLength(m)),X("ctx_execute",{content:[{type:"text",text:`${u}${hi(m,s,f?`execute:${t}:error`:`execute:${t}`)}`}],isError:f})):Buffer.byteLength(m)>xd?(Tn(Buffer.byteLength(m)),X("ctx_execute",{content:[{type:"text",text:`${u}${hi(m,"errors failures exceptions",f?`execute:${t}:error`:`execute:${t}`)}`}],isError:f})):X("ctx_execute",{content:[{type:"text",text:`${u}${m}`}],isError:f})}let p=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(p)>bd)return Tn(Buffer.byteLength(p)),X("ctx_execute",{content:[{type:"text",text:`${u}${hi(p,s,`execute:${t}`)}`}]});if(Buffer.byteLength(p)>xd){let f=dC(p,`execute:${t}`),m={...f,content:f.content.map((h,g)=>g===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return X("ctx_execute",m)}return X("ctx_execute",{content:[{type:"text",text:`${u}${p}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return X("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});bd=5e3,xd=102400;Ce.registerTool("ctx_execute_file",{title:"Run code over a file (executes code, reads the given path)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},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. +${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:f,output:m}=cb({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(m)>Ed?(En(Buffer.byteLength(m)),X("ctx_execute",{content:[{type:"text",text:`${u}${yi(m,s,f?`execute:${t}:error`:`execute:${t}`)}`}],isError:f})):Buffer.byteLength(m)>Td?(En(Buffer.byteLength(m)),X("ctx_execute",{content:[{type:"text",text:`${u}${yi(m,"errors failures exceptions",f?`execute:${t}:error`:`execute:${t}`)}`}],isError:f})):X("ctx_execute",{content:[{type:"text",text:`${u}${m}`}],isError:f})}let p=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(p)>Ed)return En(Buffer.byteLength(p)),X("ctx_execute",{content:[{type:"text",text:`${u}${yi(p,s,`execute:${t}`)}`}]});if(Buffer.byteLength(p)>Td){let f=PC(p,`execute:${t}`),m={...f,content:f.content.map((h,g)=>g===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return X("ctx_execute",m)}return X("ctx_execute",{content:[{type:"text",text:`${u}${p}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return X("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Ed=5e3,Td=102400;Ce.registerTool("ctx_execute_file",{title:"Run code over a file (executes code, reads the given path)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},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. 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. @@ -1030,7 +1035,7 @@ RETURNS: 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. 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'))") -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:j.object({path:j.string().describe("Absolute file path or relative to project root"),language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:j.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:j.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:n,timeout:r,intent:o})=>{let s=x4(t,"ctx_execute_file");if(s)return s;let i=pb(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=gb(n,"execute_file");if(a)return a}else{let a=rC(n,e,"execute_file");if(a)return a}try{let a=vd(r),c=await ic.executeFile({path:t,language:e,code:n,timeout:a}),u=uC(e,n,t);if(c.timedOut)return X("ctx_execute_file",{content:[{type:"text",text:`${u}Timed out processing ${t} after ${a}ms`}],isError:!0});if(c.exitCode!==0){let{isError:d,output:p}=Y_({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(p)>bd?(Tn(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${hi(p,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(p)>xd?(Tn(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${hi(p,"errors failures exceptions",d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):X("ctx_execute_file",{content:[{type:"text",text:`${u}${p}`}],isError:d})}let l=c.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>bd)return Tn(Buffer.byteLength(l)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${hi(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>xd){let d=dC(l,`file:${t}`),p={...d,content:d.content.map((f,m)=>m===0&&f.type==="text"?{...f,text:`${u}${f.text}`}:f)};return X("ctx_execute_file",p)}return X("ctx_execute_file",{content:[{type:"text",text:`${u}${l}`}]})}catch(a){let c=a instanceof Error?a.message:String(a);return X("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${c}`}],isError:!0})}});Ce.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},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. +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:j.object({path:j.string().describe("Absolute file path or relative to project root"),language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:j.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:j.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:n,timeout:r,intent:o})=>{let s=q4(t,"ctx_execute_file");if(s)return s;let i=Sb(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=Tb(n,"execute_file");if(a)return a}else{let a=xC(n,e,"execute_file");if(a)return a}try{let a=Pd(r),c=await uc.executeFile({path:t,language:e,code:n,timeout:a}),u=TC(e,n,t);if(c.timedOut)return X("ctx_execute_file",{content:[{type:"text",text:`${u}Timed out processing ${t} after ${a}ms`}],isError:!0});if(c.exitCode!==0){let{isError:d,output:p}=cb({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(p)>Ed?(En(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${yi(p,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(p)>Td?(En(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${yi(p,"errors failures exceptions",d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):X("ctx_execute_file",{content:[{type:"text",text:`${u}${p}`}],isError:d})}let l=c.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>Ed)return En(Buffer.byteLength(l)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${yi(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>Td){let d=PC(l,`file:${t}`),p={...d,content:d.content.map((f,m)=>m===0&&f.type==="text"?{...f,text:`${u}${f.text}`}:f)};return X("ctx_execute_file",p)}return X("ctx_execute_file",{content:[{type:"text",text:`${u}${l}`}]})}catch(a){let c=a instanceof Error?a.message:String(a);return X("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${c}`}],isError:!0})}});Ce.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},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. WHEN: - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples) @@ -1048,22 +1053,22 @@ RETURNS: 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: "