context-mode 1.0.123 → 1.0.124

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.bundle.mjs CHANGED
@@ -1,38 +1,38 @@
1
1
  #!/usr/bin/env node
2
- var uT=Object.create;var hl=Object.defineProperty;var lT=Object.getOwnPropertyDescriptor;var dT=Object.getOwnPropertyNames;var pT=Object.getPrototypeOf,mT=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Le=(t,e)=>{for(var r in e)hl(t,r,{get:e[r],enumerable:!0})},fT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dT(e))!mT.call(t,s)&&s!==r&&hl(t,s,{get:()=>e[s],enumerable:!(n=lT(e,s))||n.enumerable});return t};var Po=(t,e,r)=>(r=t!=null?uT(pT(t)):{},fT(e||!t||!t.__esModule?hl(r,"default",{value:t,enumerable:!0}):r,t));var Sl=D((eU,e_)=>{"use strict";var bl={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},wT={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},ET={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?bl.up():"");return t&&(e+=bl.left),e}};e_.exports={cursor:bl,scroll:wT,erase:ET,beep:"\x07"}});var a_=D((MU,Rl)=>{var ya=process||{},o_=ya.argv||[],ga=ya.env||{},JT=!(ga.NO_COLOR||o_.includes("--no-color"))&&(!!ga.FORCE_COLOR||o_.includes("--color")||ya.platform==="win32"||(ya.stdout||{}).isTTY&&ga.TERM!=="dumb"||!!ga.CI),YT=(t,e,r=t)=>n=>{let s=""+n,o=s.indexOf(e,t.length);return~o?t+XT(s,e,r,o)+e:t+s+e},XT=(t,e,r,n)=>{let s="",o=0;do s+=t.substring(o,n)+r,o=n+e.length,n=t.indexOf(e,o);while(~n);return s+t.substring(o)},i_=(t=JT)=>{let e=t?YT:()=>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")}};Rl.exports=i_();Rl.exports.createColors=i_});import{execFileSync as c_,execSync as Oo}from"node:child_process";import{existsSync as _a}from"node:fs";function eP(t){let e=t.split(/[\\/]/),r=e[e.length-1];return QT.test(r)}function nt(t){try{let e=Io?`where ${t}`:`command -v ${t}`;return Oo(e,{stdio:"pipe"}),!0}catch{return!1}}function Cl(t){if(Io)try{let r=Oo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(r.length===0||r.filter(s=>!/\\Microsoft\\WindowsApps\\/i.test(s)).length===0)return!1}catch{return!1}else if(!nt(t))return!1;try{return Io?Oo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):c_(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function u_(){if(nt("bun"))return!0;for(let t of l_())if(_a(t))return!0;return!1}function tP(){for(let e of l_())if(_a(e))return e;if(nt("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Io?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function l_(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Io){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function rP(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(_a(e))return e;try{let r=Oo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let s=n.toLowerCase();if(!(s.includes("system32")||s.includes("windowsapps")))return n}return null}catch{return null}}function rr(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return Oo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return c_(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function vs(){let e=u_()?tP():null,r=process.env.SHELL,n=r&&_a(r)&&eP(r)?r:null,s=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(nt("tsx")?"tsx":nt("ts-node")?"ts-node":null),python:Cl("python3")?"python3":Cl("python")?"python":Cl("py")?"py":null,shell:n??(s?rP()??(nt("sh")?"sh":nt("powershell")?"powershell":"cmd.exe"):nt("bash")?"bash":"sh"),ruby:nt("ruby")?"ruby":null,go:nt("go")?"go":null,rust:nt("rustc")?"rustc":null,php:nt("php")?"php":null,perl:nt("perl")?"perl":null,r:nt("Rscript")?"Rscript":nt("r")?"r":null,elixir:nt("elixir")?"elixir":null}}function bs(){return u_()}function xa(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${rr(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${rr(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${rr(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${rr(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${rr(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${rr(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${rr(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${rr(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${rr(t.perl)})`),t.r&&e.push(` R: ${t.r} (${rr(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${rr(t.elixir)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
- `)}function va(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"),e}function d_(t,e,r){switch(e){case"javascript":return t.javascript.endsWith("bun")?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return t.typescript?.endsWith("bun")?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let s=t.shell.toLowerCase();if(s.includes("bash")||s.endsWith("/sh")||s.endsWith("\\sh.exe")){let o=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${o}'`]}if(s.includes("powershell")||s.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r]}}var QT,Io,ba=b(()=>{"use strict";QT=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i;Io=process.platform==="win32"});function nP(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let s of n)if(s&&typeof s=="object"){let o=s.command;typeof o=="string"&&e.push(o)}}}return e}function sP(t){let e=t.match(/(?:"([^"]+\.mjs)"|'([^']+\.mjs)'|(\S+\.mjs))/);return e?.[1]??e?.[2]??e?.[3]??null}function Sa(t,e){let r=new Set,n=t.generateHookConfig(e);for(let s of Object.values(n))if(Array.isArray(s))for(let o of s)for(let i of nP(o)){let a=sP(i);a&&r.add(a)}return[...r]}var Ol=b(()=>{"use strict"});import{resolve as Ao}from"node:path";import{homedir as Il}from"node:os";import{createRequire as oP}from"node:module";function Ze(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Ao(Il(),e.replace(/^~[/\\]?/,"")):Ao(e):Ao(Il(),".claude")}function iP(t=process.env){return Ao(Ze(t),"settings.json")}function Al(t=process.env){let e=[],r=null,n=null;try{let i=oP(import.meta.url)("../adapters/detect.js");r=i.detectPlatform(),n=i.getSessionDirSegments}catch{}if(r&&n&&r.platform!=="claude-code"){let o=n(r.platform);o&&o.length>0&&e.push(Ao(Il(),...o,"settings.json"))}let s=iP(t);return e.includes(s)||e.push(s),e}var Yr=b(()=>{"use strict"});var y_,__=b(()=>{"use strict";y_={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});import{join as jl}from"node:path";import{accessSync as aP,copyFileSync as cP,constants as uP,mkdirSync as lP}from"node:fs";import{homedir as x_}from"node:os";var Se,Ct=b(()=>{"use strict";Se=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=jl(x_(),...this.sessionDirSegments,"context-mode","sessions");return lP(e,{recursive:!0}),e}getConfigDir(e){return jl(x_(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(){return jl(this.getConfigDir(),"memory")}backupSettings(){let e=this.getSettingsPath();try{aP(e,uP.R_OK);let r=e+".bak";return cP(e,r),r}catch{return null}}}});var ks,zl=b(()=>{"use strict";Ct();ks=class extends Se{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});function Ue(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}var Xr=b(()=>{"use strict"});function No(t,e){let r=ws[e],n=Fl(e);return t.hooks?.some(s=>s.command?.includes(r)||s.command?.includes(n))??!1}function Fl(t,e){if(e){let r=ws[t];return Ue(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Ul(t){let e=t.match(/"[^"]+"\s+"([^"]+\.mjs)"/);return e?e[1]:t.match(/node\s+"?([^"]+\.mjs)"?/)?.[1]??null}function S_(t){let e=Object.values(ws);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var nr,dP,Ll,v_,pP,nH,ws,b_,sH,k_=b(()=>{"use strict";Xr();nr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},dP="mcp__(?!plugin_context-mode_)",Ll=["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",dP],v_=Ll.join("|"),pP=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],nH=pP.join("|"),ws={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},b_=[nr.PRE_TOOL_USE,nr.SESSION_START],sH=[nr.POST_TOOL_USE,nr.PRE_COMPACT,nr.USER_PROMPT_SUBMIT]});var Zl={};Le(Zl,{ClaudeCodeAdapter:()=>Hl});import{readFileSync as ka,writeFileSync as w_,existsSync as mP,readdirSync as fP,chmodSync as hP,accessSync as gP,mkdirSync as yP,constants as _P}from"node:fs";import{resolve as wa,join as Es}from"node:path";import{homedir as E_}from"node:os";var Hl,Bl=b(()=>{"use strict";zl();Yr();k_();Hl=class extends ks{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 Ze()}getSessionDir(){let e=Es(this.getConfigDir(),"context-mode","sessions");return yP(e,{recursive:!0}),e}getSettingsPath(){return Es(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=`node ${e}/hooks/pretooluse.mjs`;return{PreToolUse:[...Ll].map(s=>({matcher:s,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/posttooluse.mjs`}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/precompact.mjs`}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/userpromptsubmit.mjs`}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/sessionstart.mjs`}]}]}}readSettings(){try{let e=ka(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){w_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
4
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let s=n.hooks,o=this.readPluginHooks(e),i=this.checkHookType(s,o,nr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(s,o,nr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}readPluginHooks(e){let r=[Es(e,"hooks","hooks.json"),Es(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let s=ka(n,"utf-8"),o=JSON.parse(s);if(o.hooks)return o.hooks}catch{}}checkHookType(e,r,n){let s=e?.[n];if(s&&s.length>0&&s.some(i=>No(i,n)))return!0;let o=r?.[n];return!!(o&&o.length>0&&o.some(i=>No(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(s=>s.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=Es(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(ka(r,"utf-8")).plugins??{};for(let[o,i]of Object.entries(s)){if(!o.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(),Ze(),wa(E_(),".claude"),wa(E_(),".config","claude")]));for(let r of e){let n=wa(r,"plugins","cache","context-mode","context-mode");try{let o=fP(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let d=0;d<3;d++)if((c[d]??0)!==(u[d]??0))return(c[d]??0)-(u[d]??0);return 0});if(o.length>0)return o[o.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(l=>{let p=l;if(!S_(p))return!0;let f=p.hooks??[];return f.every(h=>!h.command||!Ul(h.command))?!0:f.every(h=>{let g=h.command?Ul(h.command):null;return g?mP(g):!0})}),d=c.length-u.length;d>0&&(n[a]=u,s.push(`Removed ${d} stale ${a} hook(s)`))}let o=this.readPluginHooks(e);if(o&&b_.every(c=>this.checkHookType(void 0,o,c))){let c=Object.values(ws),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let p=0;for(let m of l){let h=m,g=h.hooks??[],_=g.length;h.hooks=g.filter(v=>!u(v.command)),p+=_-h.hooks.length}let f=l.filter(m=>{let h=m.hooks;return Array.isArray(h)&&h.length>0});(p>0||f.length!==l.length)&&(n[d]=f,p>0&&s.push(`Removed ${p} duplicate ${d} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),s.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),s}let i=[nr.PRE_TOOL_USE,nr.SESSION_START];for(let a of i){let c=Fl(a,e);if(a===nr.PRE_TOOL_USE){let u={matcher:v_,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(p=>No(p,a));l>=0?(d[l]=u,s.push(`Updated existing ${a} hook entry`)):(d.push(u),s.push(`Added ${a} hook entry`)),n.PreToolUse=d}else n.PreToolUse=[u],s.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},d=n[a];if(d&&Array.isArray(d)){let l=d.findIndex(p=>No(p,a));l>=0?(d[l]=u,s.push(`Updated existing ${a} hook entry`)):(d.push(u),s.push(`Added ${a} hook entry`)),n[a]=d}else n[a]=[u],s.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(ws)){let s=wa(e,"hooks",n);try{gP(s,_P.R_OK),hP(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Es(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(ka(n,"utf-8"));for(let[o,i]of Object.entries(s.plugins||{}))if(o.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();w_(n,JSON.stringify(s,null,2)+`
5
- `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function En(t,e){let r=ql[t];return e&&r?Ue(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var $e,$_,ql,mH,fH,T_=b(()=>{"use strict";Xr();$e={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},$_="mcp__(?!.*context-mode)",ql={[$e.BEFORE_AGENT]:"beforeagent.mjs",[$e.BEFORE_TOOL]:"beforetool.mjs",[$e.AFTER_TOOL]:"aftertool.mjs",[$e.PRE_COMPRESS]:"precompress.mjs",[$e.SESSION_START]:"sessionstart.mjs"},mH=[$e.BEFORE_TOOL,$e.SESSION_START],fH=[$e.AFTER_TOOL,$e.PRE_COMPRESS]});var R_={};Le(R_,{GeminiCLIAdapter:()=>Wl});import{readFileSync as Vl,writeFileSync as P_,mkdirSync as xP,accessSync as vP,chmodSync as bP,constants as SP}from"node:fs";import{resolve as Do,join as kP}from"node:path";import{homedir as Ea}from"node:os";var Wl,C_=b(()=>{"use strict";Ct();T_();Wl=class extends Se{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Do(Ea(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[$e.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:En($e.BEFORE_AGENT,e)}]}],[$e.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|${$_}`,hooks:[{type:"command",command:En($e.BEFORE_TOOL,e)}]}],[$e.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:En($e.AFTER_TOOL,e)}]}],[$e.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:En($e.PRE_COMPRESS,e)}]}],[$e.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:En($e.SESSION_START,e)}]}]}}readSettings(){try{let e=Vl(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Do(Ea(),".gemini");xP(r,{recursive:!0}),P_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
6
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let s=n.hooks,o=s?.[$e.BEFORE_TOOL];if(o&&o.length>0){let a=o.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=s?.[$e.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(s=>typeof s=="string"&&s.includes("context-mode")):Object.keys(r).some(s=>s.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=Do(Ea(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Vl(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[],o=[{name:$e.BEFORE_AGENT},{name:$e.BEFORE_TOOL},{name:$e.SESSION_START}];for(let i of o){let c={matcher:"",hooks:[{type:"command",command:En(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(f=>f.command?.includes("context-mode")));d>=0?(u[d]=c,s.push(`Updated existing ${i.name} hook entry`)):(u.push(c),s.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],s.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){let r=[],n=kP(e,"hooks","gemini-cli");for(let s of Object.values(ql)){let o=Do(n,s);try{vP(o,SP.R_OK),bP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Do(Ea(),".gemini","extensions","context-mode","package.json"),s=JSON.parse(Vl(n,"utf-8"));s.version=r,s.installPath=e,s.lastUpdated=new Date().toISOString(),P_(n,JSON.stringify(s,null,2)+`
7
- `,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var $n,bH,SH,O_=b(()=>{"use strict";$n={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},bH=[$n.BEFORE,$n.AFTER],SH=[$n.COMPACTING]});var A_={};Le(A_,{OpenCodeAdapter:()=>Gl});import{readFileSync as I_,writeFileSync as EP,mkdirSync as $P,copyFileSync as TP,accessSync as PP,constants as RP}from"node:fs";import{resolve as Lt,join as Qr}from"node:path";import{homedir as en}from"node:os";function wP(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Gl,N_=b(()=>{"use strict";Ct();O_();Gl=class extends Se{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??Lt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Lt("kilo.json"),Lt("kilo.jsonc"),Lt(".kilo","kilo.json"),Lt(".kilo","kilo.jsonc"),Lt(".kilocode","kilo.json"),Lt(".kilocode","kilo.jsonc"),Qr(en(),".config","kilo","kilo.json"),Qr(en(),".config","kilo","kilo.jsonc")]:[Lt("opencode.json"),Lt("opencode.jsonc"),Lt(".opencode","opencode.json"),Lt(".opencode","opencode.jsonc"),Qr(en(),".config","opencode","opencode.json"),Qr(en(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Qr(this.getConfigDir(),"context-mode","sessions");return $P(e,{recursive:!0}),e}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Qr(en(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Qr(en(),".config"),Qr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[$n.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[$n.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[$n.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(o=>o.includes(en()))),n=null,s;for(let o of e)try{let i=I_(o,"utf-8"),a=o.endsWith(".jsonc")?wP(i):i,c=JSON.parse(a);n||(n=c,s=o);let u=r.has(o);if(this.hasContextModePlugin(c)||u)return this.settingsPath=o,c}catch{continue}return n?(this.settingsPath=s,n):null}writeSettings(e){EP(this.getSettingsPath(),JSON.stringify(e,null,2)+`
8
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let s=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:s?"pass":"fail",message:s?"context-mode found in plugin array":"context-mode not found in plugin array",fix:s?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Lt(en(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(I_(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],s=r.plugin??[];return s.some(o=>o.includes("context-mode"))?n.push("context-mode already in plugin array"):(s.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=s,this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{PP(this.settingsPath,RP.R_OK);let r=this.settingsPath+".bak";return TP(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var Tn,RH,CH,D_=b(()=>{"use strict";Tn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},RH=[Tn.TOOL_CALL_BEFORE,Tn.TOOL_CALL_AFTER],CH=[Tn.COMMAND_NEW]});var M_={};Le(M_,{OpenClawAdapter:()=>Xl});import{readFileSync as Kl,writeFileSync as CP,copyFileSync as OP,accessSync as IP,constants as AP}from"node:fs";import{resolve as Or,join as Jl}from"node:path";import{homedir as Yl}from"node:os";var Xl,j_=b(()=>{"use strict";Ct();D_();Xl=class extends Se{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Or("openclaw.json")}getConfigDir(e){return Or(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(){return Jl(this.getConfigDir(),"memory")}generateHookConfig(e){return{[Tn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Tn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Tn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Or("openclaw.json"),Or(".openclaw","openclaw.json"),Jl(Yl(),".openclaw","openclaw.json")];for(let r of e)try{let n=Kl(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Or("openclaw.json");CP(r,JSON.stringify(e,null,2)+`
9
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let s=n.plugins,o=s?.entries;if(o){let a=Object.keys(o).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=o["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return s?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(o=>o.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=Or(Yl(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Kl(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Or("node_modules","context-mode","package.json"),r=JSON.parse(Kl(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let s=r.plugins;s.entries||(s.entries={});let o=s.entries;if(!o["context-mode"])o["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=o["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}s.slots||(s.slots={});let i=s.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Or("openclaw.json"),Or(".openclaw","openclaw.json"),Jl(Yl(),".openclaw","openclaw.json")];for(let r of e)try{IP(r,AP.R_OK);let n=r+".bak";return OP(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as z_}from"node:os";import{resolve as Ql}from"node:path";function $a(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Ql(z_(),t.replace(/^~[/\\]?/,"")):Ql(t):Ql(z_(),".codex")}var ed=b(()=>{"use strict"});var H_={};Le(H_,{CodexAdapter:()=>nd});import{readFileSync as $s,writeFileSync as L_,accessSync as NP,copyFileSync as DP,constants as MP,mkdirSync as td}from"node:fs";import{resolve as jP,dirname as rd,join as Ta}from"node:path";import{fileURLToPath as zP}from"node:url";function F_(t,e){let r=t.split(/\r?\n/),n=!1,s=[];for(let o of r){let i=o.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&s.push(o)}return n?s.join(`
10
- `):null}function U_(t){let e=F_(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function UP(t){let e=F_(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function HP(t){if(U_(t))return{text:t,changed:!1};let e=t.includes(`\r
2
+ var lT=Object.create;var gl=Object.defineProperty;var dT=Object.getOwnPropertyDescriptor;var pT=Object.getOwnPropertyNames;var mT=Object.getPrototypeOf,fT=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Le=(t,e)=>{for(var r in e)gl(t,r,{get:e[r],enumerable:!0})},hT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pT(e))!fT.call(t,s)&&s!==r&&gl(t,s,{get:()=>e[s],enumerable:!(n=dT(e,s))||n.enumerable});return t};var Po=(t,e,r)=>(r=t!=null?lT(mT(t)):{},hT(e||!t||!t.__esModule?gl(r,"default",{value:t,enumerable:!0}):r,t));var kl=D((iU,r_)=>{"use strict";var Sl={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ET={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},$T={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?Sl.up():"");return t&&(e+=Sl.left),e}};r_.exports={cursor:Sl,scroll:ET,erase:$T,beep:"\x07"}});var u_=D((HU,Cl)=>{var _a=process||{},a_=_a.argv||[],ya=_a.env||{},YT=!(ya.NO_COLOR||a_.includes("--no-color"))&&(!!ya.FORCE_COLOR||a_.includes("--color")||_a.platform==="win32"||(_a.stdout||{}).isTTY&&ya.TERM!=="dumb"||!!ya.CI),XT=(t,e,r=t)=>n=>{let s=""+n,o=s.indexOf(e,t.length);return~o?t+QT(s,e,r,o)+e:t+s+e},QT=(t,e,r,n)=>{let s="",o=0;do s+=t.substring(o,n)+r,o=n+e.length,n=t.indexOf(e,o);while(~n);return s+t.substring(o)},c_=(t=YT)=>{let e=t?XT:()=>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")}};Cl.exports=c_();Cl.exports.createColors=c_});import{execFileSync as l_,execSync as Oo}from"node:child_process";import{existsSync as xa}from"node:fs";function tP(t){let e=t.split(/[\\/]/),r=e[e.length-1];return eP.test(r)}function nt(t){try{let e=Io?`where ${t}`:`command -v ${t}`;return Oo(e,{stdio:"pipe"}),!0}catch{return!1}}function Ol(t){if(Io)try{let r=Oo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(r.length===0||r.filter(s=>!/\\Microsoft\\WindowsApps\\/i.test(s)).length===0)return!1}catch{return!1}else if(!nt(t))return!1;try{return Io?Oo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):l_(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function d_(){if(nt("bun"))return!0;for(let t of p_())if(xa(t))return!0;return!1}function rP(){for(let e of p_())if(xa(e))return e;if(nt("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Io?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function p_(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Io){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function nP(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(xa(e))return e;try{let r=Oo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let s=n.toLowerCase();if(!(s.includes("system32")||s.includes("windowsapps")))return n}return null}catch{return null}}function rr(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return Oo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return l_(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function bs(){let e=d_()?rP():null,r=process.env.SHELL,n=r&&xa(r)&&tP(r)?r:null,s=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(nt("tsx")?"tsx":nt("ts-node")?"ts-node":null),python:Ol("python3")?"python3":Ol("python")?"python":Ol("py")?"py":null,shell:n??(s?nP()??(nt("sh")?"sh":nt("powershell")?"powershell":"cmd.exe"):nt("bash")?"bash":"sh"),ruby:nt("ruby")?"ruby":null,go:nt("go")?"go":null,rust:nt("rustc")?"rustc":null,php:nt("php")?"php":null,perl:nt("perl")?"perl":null,r:nt("Rscript")?"Rscript":nt("r")?"r":null,elixir:nt("elixir")?"elixir":null}}function Ss(){return d_()}function va(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${rr(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${rr(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${rr(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${rr(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${rr(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${rr(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${rr(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${rr(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${rr(t.perl)})`),t.r&&e.push(` R: ${t.r} (${rr(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${rr(t.elixir)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
+ `)}function ba(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"),e}function m_(t,e,r){switch(e){case"javascript":return t.javascript.endsWith("bun")?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return t.typescript?.endsWith("bun")?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let s=t.shell.toLowerCase();if(s.includes("bash")||s.endsWith("/sh")||s.endsWith("\\sh.exe")){let o=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${o}'`]}if(s.includes("powershell")||s.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r]}}var eP,Io,Sa=b(()=>{"use strict";eP=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i;Io=process.platform==="win32"});function sP(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let s of n)if(s&&typeof s=="object"){let o=s.command;typeof o=="string"&&e.push(o)}}}return e}function oP(t){let e=t.match(/(?:"([^"]+\.mjs)"|'([^']+\.mjs)'|(\S+\.mjs))/);return e?.[1]??e?.[2]??e?.[3]??null}function ka(t,e){let r=new Set,n=t.generateHookConfig(e);for(let s of Object.values(n))if(Array.isArray(s))for(let o of s)for(let i of sP(o)){let a=oP(i);a&&r.add(a)}return[...r]}var Il=b(()=>{"use strict"});import{resolve as Ao}from"node:path";import{homedir as Al}from"node:os";import{createRequire as iP}from"node:module";function Ze(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Ao(Al(),e.replace(/^~[/\\]?/,"")):Ao(e):Ao(Al(),".claude")}function aP(t=process.env){return Ao(Ze(t),"settings.json")}function Nl(t=process.env){let e=[],r=null,n=null;try{let i=iP(import.meta.url)("../adapters/detect.js");r=i.detectPlatform(),n=i.getSessionDirSegments}catch{}if(r&&n&&r.platform!=="claude-code"){let o=n(r.platform);o&&o.length>0&&e.push(Ao(Al(),...o,"settings.json"))}let s=aP(t);return e.includes(s)||e.push(s),e}var Yr=b(()=>{"use strict"});var x_,v_=b(()=>{"use strict";x_={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});import{join as zl}from"node:path";import{accessSync as cP,copyFileSync as uP,constants as lP,mkdirSync as dP}from"node:fs";import{homedir as b_}from"node:os";var Se,Ct=b(()=>{"use strict";Se=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=zl(b_(),...this.sessionDirSegments,"context-mode","sessions");return dP(e,{recursive:!0}),e}getConfigDir(e){return zl(b_(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(){return zl(this.getConfigDir(),"memory")}backupSettings(){let e=this.getSettingsPath();try{cP(e,lP.R_OK);let r=e+".bak";return uP(e,r),r}catch{return null}}}});var ws,Ll=b(()=>{"use strict";Ct();ws=class extends Se{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});function Ue(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}var Xr=b(()=>{"use strict"});function No(t,e){let r=Es[e],n=Ul(e);return t.hooks?.some(s=>s.command?.includes(r)||s.command?.includes(n))??!1}function Ul(t,e){if(e){let r=Es[t];return Ue(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Hl(t){let e=t.match(/"[^"]+"\s+"([^"]+\.mjs)"/);return e?e[1]:t.match(/node\s+"?([^"]+\.mjs)"?/)?.[1]??null}function w_(t){let e=Object.values(Es);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var nr,pP,Fl,S_,mP,uH,Es,k_,lH,E_=b(()=>{"use strict";Xr();nr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},pP="mcp__(?!plugin_context-mode_)",Fl=["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",pP],S_=Fl.join("|"),mP=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],uH=mP.join("|"),Es={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},k_=[nr.PRE_TOOL_USE,nr.SESSION_START],lH=[nr.POST_TOOL_USE,nr.PRE_COMPACT,nr.USER_PROMPT_SUBMIT]});var Bl={};Le(Bl,{ClaudeCodeAdapter:()=>Zl});import{readFileSync as wa,writeFileSync as $_,existsSync as fP,readdirSync as hP,chmodSync as gP,accessSync as yP,mkdirSync as _P,constants as xP}from"node:fs";import{resolve as Ea,join as $s}from"node:path";import{homedir as T_}from"node:os";var Zl,ql=b(()=>{"use strict";Ll();Yr();E_();Zl=class extends ws{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 Ze()}getSessionDir(){let e=$s(this.getConfigDir(),"context-mode","sessions");return _P(e,{recursive:!0}),e}getSettingsPath(){return $s(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=`node ${e}/hooks/pretooluse.mjs`;return{PreToolUse:[...Fl].map(s=>({matcher:s,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/posttooluse.mjs`}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/precompact.mjs`}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/userpromptsubmit.mjs`}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/sessionstart.mjs`}]}]}}readSettings(){try{let e=wa(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){$_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
4
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let s=n.hooks,o=this.readPluginHooks(e),i=this.checkHookType(s,o,nr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(s,o,nr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}readPluginHooks(e){let r=[$s(e,"hooks","hooks.json"),$s(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let s=wa(n,"utf-8"),o=JSON.parse(s);if(o.hooks)return o.hooks}catch{}}checkHookType(e,r,n){let s=e?.[n];if(s&&s.length>0&&s.some(i=>No(i,n)))return!0;let o=r?.[n];return!!(o&&o.length>0&&o.some(i=>No(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(s=>s.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=$s(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(wa(r,"utf-8")).plugins??{};for(let[o,i]of Object.entries(s)){if(!o.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(),Ze(),Ea(T_(),".claude"),Ea(T_(),".config","claude")]));for(let r of e){let n=Ea(r,"plugins","cache","context-mode","context-mode");try{let o=hP(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let d=0;d<3;d++)if((c[d]??0)!==(u[d]??0))return(c[d]??0)-(u[d]??0);return 0});if(o.length>0)return o[o.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(l=>{let p=l;if(!w_(p))return!0;let f=p.hooks??[];return f.every(h=>!h.command||!Hl(h.command))?!0:f.every(h=>{let g=h.command?Hl(h.command):null;return g?fP(g):!0})}),d=c.length-u.length;d>0&&(n[a]=u,s.push(`Removed ${d} stale ${a} hook(s)`))}let o=this.readPluginHooks(e);if(o&&k_.every(c=>this.checkHookType(void 0,o,c))){let c=Object.values(Es),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let p=0;for(let m of l){let h=m,g=h.hooks??[],_=g.length;h.hooks=g.filter(v=>!u(v.command)),p+=_-h.hooks.length}let f=l.filter(m=>{let h=m.hooks;return Array.isArray(h)&&h.length>0});(p>0||f.length!==l.length)&&(n[d]=f,p>0&&s.push(`Removed ${p} duplicate ${d} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),s.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),s}let i=[nr.PRE_TOOL_USE,nr.SESSION_START];for(let a of i){let c=Ul(a,e);if(a===nr.PRE_TOOL_USE){let u={matcher:S_,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(p=>No(p,a));l>=0?(d[l]=u,s.push(`Updated existing ${a} hook entry`)):(d.push(u),s.push(`Added ${a} hook entry`)),n.PreToolUse=d}else n.PreToolUse=[u],s.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},d=n[a];if(d&&Array.isArray(d)){let l=d.findIndex(p=>No(p,a));l>=0?(d[l]=u,s.push(`Updated existing ${a} hook entry`)):(d.push(u),s.push(`Added ${a} hook entry`)),n[a]=d}else n[a]=[u],s.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(Es)){let s=Ea(e,"hooks",n);try{yP(s,xP.R_OK),gP(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=$s(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(wa(n,"utf-8"));for(let[o,i]of Object.entries(s.plugins||{}))if(o.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();$_(n,JSON.stringify(s,null,2)+`
5
+ `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function En(t,e){let r=Vl[t];return e&&r?Ue(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var $e,P_,Vl,xH,vH,R_=b(()=>{"use strict";Xr();$e={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},P_="mcp__(?!.*context-mode)",Vl={[$e.BEFORE_AGENT]:"beforeagent.mjs",[$e.BEFORE_TOOL]:"beforetool.mjs",[$e.AFTER_TOOL]:"aftertool.mjs",[$e.PRE_COMPRESS]:"precompress.mjs",[$e.SESSION_START]:"sessionstart.mjs"},xH=[$e.BEFORE_TOOL,$e.SESSION_START],vH=[$e.AFTER_TOOL,$e.PRE_COMPRESS]});var O_={};Le(O_,{GeminiCLIAdapter:()=>Gl});import{readFileSync as Wl,writeFileSync as C_,mkdirSync as vP,accessSync as bP,chmodSync as SP,constants as kP}from"node:fs";import{resolve as Do,join as wP}from"node:path";import{homedir as $a}from"node:os";var Gl,I_=b(()=>{"use strict";Ct();R_();Gl=class extends Se{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Do($a(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[$e.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:En($e.BEFORE_AGENT,e)}]}],[$e.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|${P_}`,hooks:[{type:"command",command:En($e.BEFORE_TOOL,e)}]}],[$e.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:En($e.AFTER_TOOL,e)}]}],[$e.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:En($e.PRE_COMPRESS,e)}]}],[$e.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:En($e.SESSION_START,e)}]}]}}readSettings(){try{let e=Wl(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Do($a(),".gemini");vP(r,{recursive:!0}),C_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
6
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let s=n.hooks,o=s?.[$e.BEFORE_TOOL];if(o&&o.length>0){let a=o.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=s?.[$e.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(s=>typeof s=="string"&&s.includes("context-mode")):Object.keys(r).some(s=>s.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=Do($a(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Wl(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[],o=[{name:$e.BEFORE_AGENT},{name:$e.BEFORE_TOOL},{name:$e.SESSION_START}];for(let i of o){let c={matcher:"",hooks:[{type:"command",command:En(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(f=>f.command?.includes("context-mode")));d>=0?(u[d]=c,s.push(`Updated existing ${i.name} hook entry`)):(u.push(c),s.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],s.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){let r=[],n=wP(e,"hooks","gemini-cli");for(let s of Object.values(Vl)){let o=Do(n,s);try{bP(o,kP.R_OK),SP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Do($a(),".gemini","extensions","context-mode","package.json"),s=JSON.parse(Wl(n,"utf-8"));s.version=r,s.installPath=e,s.lastUpdated=new Date().toISOString(),C_(n,JSON.stringify(s,null,2)+`
7
+ `,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var $n,TH,PH,A_=b(()=>{"use strict";$n={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},TH=[$n.BEFORE,$n.AFTER],PH=[$n.COMPACTING]});var D_={};Le(D_,{OpenCodeAdapter:()=>Kl});import{readFileSync as N_,writeFileSync as $P,mkdirSync as TP,copyFileSync as PP,accessSync as RP,constants as CP}from"node:fs";import{resolve as Lt,join as Qr}from"node:path";import{homedir as en}from"node:os";function EP(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Kl,M_=b(()=>{"use strict";Ct();A_();Kl=class extends Se{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??Lt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Lt("kilo.json"),Lt("kilo.jsonc"),Lt(".kilo","kilo.json"),Lt(".kilo","kilo.jsonc"),Lt(".kilocode","kilo.json"),Lt(".kilocode","kilo.jsonc"),Qr(en(),".config","kilo","kilo.json"),Qr(en(),".config","kilo","kilo.jsonc")]:[Lt("opencode.json"),Lt("opencode.jsonc"),Lt(".opencode","opencode.json"),Lt(".opencode","opencode.jsonc"),Qr(en(),".config","opencode","opencode.json"),Qr(en(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Qr(this.getConfigDir(),"context-mode","sessions");return TP(e,{recursive:!0}),e}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Qr(en(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Qr(en(),".config"),Qr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[$n.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[$n.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[$n.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(o=>o.includes(en()))),n=null,s;for(let o of e)try{let i=N_(o,"utf-8"),a=o.endsWith(".jsonc")?EP(i):i,c=JSON.parse(a);n||(n=c,s=o);let u=r.has(o);if(this.hasContextModePlugin(c)||u)return this.settingsPath=o,c}catch{continue}return n?(this.settingsPath=s,n):null}writeSettings(e){$P(this.getSettingsPath(),JSON.stringify(e,null,2)+`
8
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let s=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:s?"pass":"fail",message:s?"context-mode found in plugin array":"context-mode not found in plugin array",fix:s?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Lt(en(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(N_(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],s=r.plugin??[];return s.some(o=>o.includes("context-mode"))?n.push("context-mode already in plugin array"):(s.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=s,this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{RP(this.settingsPath,CP.R_OK);let r=this.settingsPath+".bak";return PP(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var Tn,DH,MH,j_=b(()=>{"use strict";Tn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},DH=[Tn.TOOL_CALL_BEFORE,Tn.TOOL_CALL_AFTER],MH=[Tn.COMMAND_NEW]});var z_={};Le(z_,{OpenClawAdapter:()=>Ql});import{readFileSync as Jl,writeFileSync as OP,copyFileSync as IP,accessSync as AP,constants as NP}from"node:fs";import{resolve as Or,join as Yl}from"node:path";import{homedir as Xl}from"node:os";var Ql,L_=b(()=>{"use strict";Ct();j_();Ql=class extends Se{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Or("openclaw.json")}getConfigDir(e){return Or(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(){return Yl(this.getConfigDir(),"memory")}generateHookConfig(e){return{[Tn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Tn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Tn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Or("openclaw.json"),Or(".openclaw","openclaw.json"),Yl(Xl(),".openclaw","openclaw.json")];for(let r of e)try{let n=Jl(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Or("openclaw.json");OP(r,JSON.stringify(e,null,2)+`
9
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let s=n.plugins,o=s?.entries;if(o){let a=Object.keys(o).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=o["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return s?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(o=>o.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=Or(Xl(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Jl(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Or("node_modules","context-mode","package.json"),r=JSON.parse(Jl(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let s=r.plugins;s.entries||(s.entries={});let o=s.entries;if(!o["context-mode"])o["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=o["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}s.slots||(s.slots={});let i=s.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Or("openclaw.json"),Or(".openclaw","openclaw.json"),Yl(Xl(),".openclaw","openclaw.json")];for(let r of e)try{AP(r,NP.R_OK);let n=r+".bak";return IP(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as F_}from"node:os";import{resolve as ed}from"node:path";function Ta(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?ed(F_(),t.replace(/^~[/\\]?/,"")):ed(t):ed(F_(),".codex")}var td=b(()=>{"use strict"});var B_={};Le(B_,{CodexAdapter:()=>sd});import{readFileSync as Ts,writeFileSync as U_,accessSync as DP,copyFileSync as MP,constants as jP,mkdirSync as rd}from"node:fs";import{resolve as zP,dirname as nd,join as Pa}from"node:path";import{fileURLToPath as LP}from"node:url";function H_(t,e){let r=t.split(/\r?\n/),n=!1,s=[];for(let o of r){let i=o.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&s.push(o)}return n?s.join(`
10
+ `):null}function Z_(t){let e=H_(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function HP(t){let e=H_(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function ZP(t){if(Z_(t))return{text:t,changed:!1};let e=t.includes(`\r
11
11
  `)?`\r
12
12
  `:`
13
13
  `,r=t.split(/\r?\n/),n=r.findIndex(o=>/^\s*\[features\]\s*(?:#.*)?$/.test(o));if(n===-1){let o=t.length>0&&!t.endsWith(`
14
- `)?e:"";return{text:`${t}${o}[features]${e}hooks = true${e}`,changed:!0}}let s=r.length;for(let o=n+1;o<r.length;o++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[o]??"")){s=o;break}for(let o=n+1;o<s;o++)if(/^\s*hooks\s*=/.test(r[o]??""))return r[o]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var LP,Pn,FP,nd,Z_=b(()=>{"use strict";Ct();ed();LP="local_shell|shell|shell_command|exec_command|container.exec|functions\\.exec_command|Bash|Shell|apply_patch|functions\\.apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__.*__ctx_execute|mcp__.*__ctx_execute_file|mcp__.*__ctx_batch_execute|mcp__.*__ctx_fetch_and_index|mcp__.*__ctx_search|mcp__.*__ctx_index|mcp__(?!.*context-mode)",Pn={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"},FP={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"]};nd=class extends Se{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return $a()}getSettingsPath(){return Ta(this.getConfigDir(),"config.toml")}getSessionDir(){let e=Ta(this.getConfigDir(),"context-mode","sessions");return td(e,{recursive:!0}),e}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(){return Ta(this.getConfigDir(),"memories")}generateHookConfig(e){return{PreToolUse:[{matcher:LP,hooks:[{type:"command",command:Pn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Pn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Pn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Pn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Pn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Pn.Stop}]}]}}readSettings(){try{return{_raw_toml:$s(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[];try{let o=$s(this.getSettingsPath(),"utf-8"),i=U_(o),a=!i&&UP(o);r.push({check:"Codex hooks feature flag",status:i?"pass":"fail",message:i?`[features].hooks enabled in ${this.getSettingsPath()}`:a?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...i?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let n=this.readHooksConfig();if(!n.ok)return n.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):n.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${n.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${n.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!n.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let s=this.generateHookConfig("");return r.concat(Object.entries(s).map(([o,i])=>{let a=n.config.hooks?.[o],c=i[0],u=Array.isArray(a)&&a.some(l=>this.isExpectedHookEntry(o,l,c)),d=o==="PreCompact"?"warn":"fail";return{check:`${o} hook`,status:u?"pass":d,message:u?`${o} hook configured in ${this.getHooksPath()}`:o==="PreCompact"?`${o} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${o} hook missing or not pointing to context-mode`,fix:u?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}))}checkPluginRegistration(){try{let e=$s(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],s;if(r.ok)s=r.config;else if(r.reason==="missing")s={hooks:{}};else if(r.reason==="invalid_json"){let d=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${d}`),s={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let o=s.hooks&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)?s.hooks:{},i=this.generateHookConfig(e);for(let[d,l]of Object.entries(i))this.upsertManagedHookEntry(o,d,l[0],n);n.length>0&&(s.hooks=o,this.writeHooksConfig(s),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=$s(a,"utf-8")}catch{c=""}let u=HP(c);if(u.changed){let d=u.text.includes(`\r
14
+ `)?e:"";return{text:`${t}${o}[features]${e}hooks = true${e}`,changed:!0}}let s=r.length;for(let o=n+1;o<r.length;o++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[o]??"")){s=o;break}for(let o=n+1;o<s;o++)if(/^\s*hooks\s*=/.test(r[o]??""))return r[o]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var FP,Pn,UP,sd,q_=b(()=>{"use strict";Ct();td();FP="local_shell|shell|shell_command|exec_command|container.exec|functions\\.exec_command|Bash|Shell|apply_patch|functions\\.apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__.*__ctx_execute|mcp__.*__ctx_execute_file|mcp__.*__ctx_batch_execute|mcp__.*__ctx_fetch_and_index|mcp__.*__ctx_search|mcp__.*__ctx_index|mcp__(?!.*context-mode)",Pn={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"},UP={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"]};sd=class extends Se{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return Ta()}getSettingsPath(){return Pa(this.getConfigDir(),"config.toml")}getSessionDir(){let e=Pa(this.getConfigDir(),"context-mode","sessions");return rd(e,{recursive:!0}),e}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(){return Pa(this.getConfigDir(),"memories")}generateHookConfig(e){return{PreToolUse:[{matcher:FP,hooks:[{type:"command",command:Pn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Pn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Pn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Pn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Pn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Pn.Stop}]}]}}readSettings(){try{return{_raw_toml:Ts(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[];try{let o=Ts(this.getSettingsPath(),"utf-8"),i=Z_(o),a=!i&&HP(o);r.push({check:"Codex hooks feature flag",status:i?"pass":"fail",message:i?`[features].hooks enabled in ${this.getSettingsPath()}`:a?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...i?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let n=this.readHooksConfig();if(!n.ok)return n.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):n.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${n.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${n.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!n.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let s=this.generateHookConfig("");return r.concat(Object.entries(s).map(([o,i])=>{let a=n.config.hooks?.[o],c=i[0],u=Array.isArray(a)&&a.some(l=>this.isExpectedHookEntry(o,l,c)),d=o==="PreCompact"?"warn":"fail";return{check:`${o} hook`,status:u?"pass":d,message:u?`${o} hook configured in ${this.getHooksPath()}`:o==="PreCompact"?`${o} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${o} hook missing or not pointing to context-mode`,fix:u?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}))}checkPluginRegistration(){try{let e=Ts(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],s;if(r.ok)s=r.config;else if(r.reason==="missing")s={hooks:{}};else if(r.reason==="invalid_json"){let d=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${d}`),s={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let o=s.hooks&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)?s.hooks:{},i=this.generateHookConfig(e);for(let[d,l]of Object.entries(i))this.upsertManagedHookEntry(o,d,l[0],n);n.length>0&&(s.hooks=o,this.writeHooksConfig(s),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=Ts(a,"utf-8")}catch{c=""}let u=ZP(c);if(u.changed){let d=u.text.includes(`\r
15
15
  `)?`\r
16
16
  `:`
17
17
  `,l=u.text.endsWith(`
18
- `)?u.text:`${u.text}${d}`;td(rd(a),{recursive:!0}),L_(a,l,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{NP(r,MP.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=jP(rd(zP(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return $s(e,"utf-8")}catch{return`# context-mode
18
+ `)?u.text:`${u.text}${d}`;rd(nd(a),{recursive:!0}),U_(a,l,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{DP(r,jP.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=zP(nd(LP(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return Ts(e,"utf-8")}catch{return`# context-mode
19
19
 
20
- 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 Ta(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return DP(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse($s(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();td(rd(r),{recursive:!0}),L_(r,JSON.stringify(e,null,2)+`
21
- `,"utf-8")}upsertManagedHookEntry(e,r,n,s){let o=Array.isArray(e[r])?[...e[r]]:[],i=o.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){o.push(n),e[r]=o,s.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(o[a])!==JSON.stringify(n)&&(o[a]=n,s.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())o.splice(c,1),s.push(`Removed duplicate ${r} context-mode hook`);e[r]=o}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),s=this.normalizeCommand(Pn[e]??""),o=FP[e]??[];return n.some(i=>i.includes(s)||o.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 B_,writeFileSync as ZP,mkdirSync as BP,accessSync as qP,chmodSync as VP,constants as WP}from"node:fs";import{resolve as Pa,join as GP}from"node:path";var Ts,sd=b(()=>{"use strict";Ct();Ts=class extends Se{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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 Pa(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=B_(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=B_(Pa(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();BP(Pa(".github","hooks"),{recursive:!0}),ZP(r,JSON.stringify(e,null,2)+`
22
- `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},s=n.hooks??{},{HOOK_TYPES:o,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[o.PRE_TOOL_USE,o.POST_TOOL_USE,o.PRE_COMPACT,o.SESSION_START];for(let u of c)i[u]&&(s[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=s,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=GP(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=Pa(n,s);try{qP(o,WP.R_OK),VP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function q_(t,e){let r=od[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Ue(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Ft,od,JH,YH,V_=b(()=>{"use strict";Xr();Ft={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},od={[Ft.PRE_TOOL_USE]:"pretooluse.mjs",[Ft.POST_TOOL_USE]:"posttooluse.mjs",[Ft.PRE_COMPACT]:"precompact.mjs",[Ft.SESSION_START]:"sessionstart.mjs"},JH=[Ft.PRE_TOOL_USE,Ft.SESSION_START],YH=[Ft.POST_TOOL_USE,Ft.PRE_COMPACT]});var W_={};Le(W_,{VSCodeCopilotAdapter:()=>cd});import{readFileSync as id,mkdirSync as KP,accessSync as JP,existsSync as YP,constants as XP}from"node:fs";import{resolve as Ps,join as Ra}from"node:path";import{homedir as ad}from"node:os";var cd,G_=b(()=>{"use strict";sd();V_();cd=class extends Ts{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Ft,HOOK_SCRIPTS:od,buildHookCommand:q_};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.cwd()}getSessionDir(){let e=Ps(".github","context-mode","sessions"),r=Ra(ad(),".vscode","context-mode","sessions"),n=YP(Ps(".github"))?e:r;return KP(n,{recursive:!0}),n}getConfigDir(e){return Ps(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=Ps(".github","hooks");try{JP(n,XP.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=Ps(n,"context-mode.json");try{let o=id(s,"utf-8"),a=JSON.parse(o).hooks;a?.[Ft.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Ft.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=Ps(".vscode","mcp.json"),r=id(e,"utf-8"),s=JSON.parse(r).servers;return s&&Object.keys(s).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=[Ra(ad(),".vscode","extensions"),Ra(ad(),".vscode-insiders","extensions")];for(let r of e)try{let n=id(Ra(r,"extensions.json"),"utf-8"),o=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(o&&typeof o.version=="string")return o.version}catch{continue}return"not installed"}}});function K_(t,e){let r=ud[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Ue(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Ut,ud,oZ,iZ,J_=b(()=>{"use strict";Xr();Ut={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},ud={[Ut.PRE_TOOL_USE]:"pretooluse.mjs",[Ut.POST_TOOL_USE]:"posttooluse.mjs",[Ut.PRE_COMPACT]:"precompact.mjs",[Ut.SESSION_START]:"sessionstart.mjs"},oZ=[Ut.PRE_TOOL_USE,Ut.SESSION_START],iZ=[Ut.POST_TOOL_USE,Ut.PRE_COMPACT]});var Y_={};Le(Y_,{JetBrainsCopilotAdapter:()=>ld});import{readFileSync as QP}from"node:fs";import{resolve as eR}from"node:path";var ld,X_=b(()=>{"use strict";sd();J_();ld=class extends Ts{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Ut,HOOK_SCRIPTS:ud,buildHookCommand:K_};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 eR(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=QP(this.getSettingsPath(),"utf-8"),o=JSON.parse(n).hooks;o?.[Ut.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),o?.[Ut.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Mo(t,e){let r=dd[e],n=Ht(e);if("command"in t){let o=t.command??"";return r!=null&&o.includes(r)||o.includes(n)}return t.hooks?.some(o=>{let i=o.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Ht(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,dd,tR,rR,pd,Q_,ex,tx=b(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},dd={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},tR="MCP:(?!ctx_)",rR=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",tR],pd=rR.join("|"),Q_=[_e.PRE_TOOL_USE],ex=[_e.POST_TOOL_USE]});var ix={};Le(ix,{CursorAdapter:()=>md});import{readFileSync as Ca,writeFileSync as nR,mkdirSync as sR,accessSync as rx,chmodSync as oR,constants as nx,existsSync as sx,readdirSync as iR}from"node:fs";import{execSync as aR}from"node:child_process";import{resolve as Rn,join as Cn}from"node:path";import{homedir as Oa}from"node:os";var ox,md,ax=b(()=>{"use strict";Ct();Yr();tx();ox="/Library/Application Support/Cursor/hooks.json",md=class extends Se{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return Rn(".cursor","hooks.json")}getConfigDir(e){return Rn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Ht(_e.PRE_TOOL_USE),matcher:pd,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Ht(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Ht(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Ht(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ht(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ca(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();sR(Rn(".cursor"),{recursive:!0}),nR(r,JSON.stringify(e,null,2)+`
23
- `,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let o=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of Q_){let a=o[i],c=Array.isArray(a)&&a.some(u=>Mo(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of ex){let a=o[i],c=Array.isArray(a)&&a.some(u=>Mo(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}sx(ox)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let s=this.detectPluginInstalls();return s.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Mo(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${s[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${s[0]}`})),r}detectPluginInstalls(){let e=[Cn(Oa(),".cursor","plugins","local"),Cn(Oa(),".cursor","plugins","cache")],r=[];for(let n of e){try{rx(n,nx.F_OK)}catch{continue}let s=[];try{s=iR(n)}catch{continue}for(let o of s){let i=Cn(n,o,".cursor-plugin","plugin.json");try{let a=Ca(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Rn(".cursor","mcp.json"),Cn(Oa(),".cursor","mcp.json")];for(let n of e)try{let s=Ca(n,"utf-8"),o=JSON.parse(s),i=o.mcpServers??o.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return aR("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},s=[];return this.upsertHookEntry(n,_e.PRE_TOOL_USE,{type:"command",command:Ht(_e.PRE_TOOL_USE),matcher:pd,loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.POST_TOOL_USE,{type:"command",command:Ht(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.SESSION_START,{type:"command",command:Ht(_e.SESSION_START),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.STOP,{type:"command",command:Ht(_e.STOP),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Ht(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},s),r.version=1,r.hooks=n,this.writeSettings(r),s.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),s}setHookPermissions(e){let r=[],n=Cn(e,"hooks","cursor");for(let s of Object.values(dd)){let o=Rn(n,s);try{rx(o,nx.R_OK),oR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),Cn(Oa(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(ox),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ca(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Rn(".claude","settings.json"),Rn(".claude","settings.local.json"),Cn(Ze(),"settings.json")].some(r=>sx(r))}upsertHookEntry(e,r,n,s){let o=e[r],i=Array.isArray(o)?[...o]:[],a=i.findIndex(c=>Mo(c,r));a>=0?(i[a]=n,s.push(`Updated existing ${r} hook entry`)):(i.push(n),s.push(`Added ${r} hook entry`)),e[r]=i}}});var ux={};Le(ux,{AntigravityAdapter:()=>hd});import{readFileSync as Ia,writeFileSync as cR,mkdirSync as uR}from"node:fs";import{resolve as Aa,dirname as cx}from"node:path";import{fileURLToPath as lR}from"node:url";import{homedir as fd}from"node:os";var hd,lx=b(()=>{"use strict";Ct();hd=class extends Se{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Aa(fd(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Aa(fd(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Ia(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();uR(cx(r),{recursive:!0}),cR(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Ia(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=Aa(fd(),".gemini","extensions","context-mode","package.json");return JSON.parse(Ia(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Aa(cx(lR(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Ia(e,"utf-8")}catch{return`# context-mode
20
+ 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 Pa(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return MP(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(Ts(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();rd(nd(r),{recursive:!0}),U_(r,JSON.stringify(e,null,2)+`
21
+ `,"utf-8")}upsertManagedHookEntry(e,r,n,s){let o=Array.isArray(e[r])?[...e[r]]:[],i=o.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){o.push(n),e[r]=o,s.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(o[a])!==JSON.stringify(n)&&(o[a]=n,s.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())o.splice(c,1),s.push(`Removed duplicate ${r} context-mode hook`);e[r]=o}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),s=this.normalizeCommand(Pn[e]??""),o=UP[e]??[];return n.some(i=>i.includes(s)||o.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 V_,writeFileSync as BP,mkdirSync as qP,accessSync as VP,chmodSync as WP,constants as GP}from"node:fs";import{resolve as Ra,join as KP}from"node:path";var Ps,od=b(()=>{"use strict";Ct();Ps=class extends Se{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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 Ra(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=V_(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=V_(Ra(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();qP(Ra(".github","hooks"),{recursive:!0}),BP(r,JSON.stringify(e,null,2)+`
22
+ `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},s=n.hooks??{},{HOOK_TYPES:o,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[o.PRE_TOOL_USE,o.POST_TOOL_USE,o.PRE_COMPACT,o.SESSION_START];for(let u of c)i[u]&&(s[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=s,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=KP(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=Ra(n,s);try{VP(o,GP.R_OK),WP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function W_(t,e){let r=id[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Ue(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Ft,id,rZ,nZ,G_=b(()=>{"use strict";Xr();Ft={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},id={[Ft.PRE_TOOL_USE]:"pretooluse.mjs",[Ft.POST_TOOL_USE]:"posttooluse.mjs",[Ft.PRE_COMPACT]:"precompact.mjs",[Ft.SESSION_START]:"sessionstart.mjs"},rZ=[Ft.PRE_TOOL_USE,Ft.SESSION_START],nZ=[Ft.POST_TOOL_USE,Ft.PRE_COMPACT]});var K_={};Le(K_,{VSCodeCopilotAdapter:()=>ud});import{readFileSync as ad,mkdirSync as JP,accessSync as YP,existsSync as XP,constants as QP}from"node:fs";import{resolve as Rs,join as Ca}from"node:path";import{homedir as cd}from"node:os";var ud,J_=b(()=>{"use strict";od();G_();ud=class extends Ps{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Ft,HOOK_SCRIPTS:id,buildHookCommand:W_};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.cwd()}getSessionDir(){let e=Rs(".github","context-mode","sessions"),r=Ca(cd(),".vscode","context-mode","sessions"),n=XP(Rs(".github"))?e:r;return JP(n,{recursive:!0}),n}getConfigDir(e){return Rs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=Rs(".github","hooks");try{YP(n,QP.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=Rs(n,"context-mode.json");try{let o=ad(s,"utf-8"),a=JSON.parse(o).hooks;a?.[Ft.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Ft.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=Rs(".vscode","mcp.json"),r=ad(e,"utf-8"),s=JSON.parse(r).servers;return s&&Object.keys(s).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=[Ca(cd(),".vscode","extensions"),Ca(cd(),".vscode-insiders","extensions")];for(let r of e)try{let n=ad(Ca(r,"extensions.json"),"utf-8"),o=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(o&&typeof o.version=="string")return o.version}catch{continue}return"not installed"}}});function Y_(t,e){let r=ld[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Ue(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Ut,ld,dZ,pZ,X_=b(()=>{"use strict";Xr();Ut={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},ld={[Ut.PRE_TOOL_USE]:"pretooluse.mjs",[Ut.POST_TOOL_USE]:"posttooluse.mjs",[Ut.PRE_COMPACT]:"precompact.mjs",[Ut.SESSION_START]:"sessionstart.mjs"},dZ=[Ut.PRE_TOOL_USE,Ut.SESSION_START],pZ=[Ut.POST_TOOL_USE,Ut.PRE_COMPACT]});var Q_={};Le(Q_,{JetBrainsCopilotAdapter:()=>dd});import{readFileSync as eR}from"node:fs";import{resolve as tR}from"node:path";var dd,ex=b(()=>{"use strict";od();X_();dd=class extends Ps{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Ut,HOOK_SCRIPTS:ld,buildHookCommand:Y_};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 tR(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=eR(this.getSettingsPath(),"utf-8"),o=JSON.parse(n).hooks;o?.[Ut.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),o?.[Ut.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Mo(t,e){let r=pd[e],n=Ht(e);if("command"in t){let o=t.command??"";return r!=null&&o.includes(r)||o.includes(n)}return t.hooks?.some(o=>{let i=o.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Ht(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,pd,rR,nR,md,tx,rx,nx=b(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},pd={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},rR="MCP:(?!ctx_)",nR=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",rR],md=nR.join("|"),tx=[_e.PRE_TOOL_USE],rx=[_e.POST_TOOL_USE]});var cx={};Le(cx,{CursorAdapter:()=>fd});import{readFileSync as Oa,writeFileSync as sR,mkdirSync as oR,accessSync as sx,chmodSync as iR,constants as ox,existsSync as ix,readdirSync as aR}from"node:fs";import{execSync as cR}from"node:child_process";import{resolve as Rn,join as Cn}from"node:path";import{homedir as Ia}from"node:os";var ax,fd,ux=b(()=>{"use strict";Ct();Yr();nx();ax="/Library/Application Support/Cursor/hooks.json",fd=class extends Se{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return Rn(".cursor","hooks.json")}getConfigDir(e){return Rn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Ht(_e.PRE_TOOL_USE),matcher:md,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Ht(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Ht(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Ht(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ht(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Oa(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();oR(Rn(".cursor"),{recursive:!0}),sR(r,JSON.stringify(e,null,2)+`
23
+ `,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let o=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of tx){let a=o[i],c=Array.isArray(a)&&a.some(u=>Mo(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of rx){let a=o[i],c=Array.isArray(a)&&a.some(u=>Mo(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}ix(ax)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let s=this.detectPluginInstalls();return s.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Mo(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${s[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${s[0]}`})),r}detectPluginInstalls(){let e=[Cn(Ia(),".cursor","plugins","local"),Cn(Ia(),".cursor","plugins","cache")],r=[];for(let n of e){try{sx(n,ox.F_OK)}catch{continue}let s=[];try{s=aR(n)}catch{continue}for(let o of s){let i=Cn(n,o,".cursor-plugin","plugin.json");try{let a=Oa(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Rn(".cursor","mcp.json"),Cn(Ia(),".cursor","mcp.json")];for(let n of e)try{let s=Oa(n,"utf-8"),o=JSON.parse(s),i=o.mcpServers??o.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return cR("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},s=[];return this.upsertHookEntry(n,_e.PRE_TOOL_USE,{type:"command",command:Ht(_e.PRE_TOOL_USE),matcher:md,loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.POST_TOOL_USE,{type:"command",command:Ht(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.SESSION_START,{type:"command",command:Ht(_e.SESSION_START),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.STOP,{type:"command",command:Ht(_e.STOP),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Ht(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},s),r.version=1,r.hooks=n,this.writeSettings(r),s.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),s}setHookPermissions(e){let r=[],n=Cn(e,"hooks","cursor");for(let s of Object.values(pd)){let o=Rn(n,s);try{sx(o,ox.R_OK),iR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),Cn(Ia(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(ax),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=Oa(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Rn(".claude","settings.json"),Rn(".claude","settings.local.json"),Cn(Ze(),"settings.json")].some(r=>ix(r))}upsertHookEntry(e,r,n,s){let o=e[r],i=Array.isArray(o)?[...o]:[],a=i.findIndex(c=>Mo(c,r));a>=0?(i[a]=n,s.push(`Updated existing ${r} hook entry`)):(i.push(n),s.push(`Added ${r} hook entry`)),e[r]=i}}});var dx={};Le(dx,{AntigravityAdapter:()=>gd});import{readFileSync as Aa,writeFileSync as uR,mkdirSync as lR}from"node:fs";import{resolve as Na,dirname as lx}from"node:path";import{fileURLToPath as dR}from"node:url";import{homedir as hd}from"node:os";var gd,px=b(()=>{"use strict";Ct();gd=class extends Se{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Na(hd(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Na(hd(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Aa(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();lR(lx(r),{recursive:!0}),uR(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Aa(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=Na(hd(),".gemini","extensions","context-mode","package.json");return JSON.parse(Aa(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Na(lx(dR(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Aa(e,"utf-8")}catch{return`# context-mode
24
24
 
25
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function Na(t,e){let r=dx[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function Rs(t,e){let r=dx[t];return e&&r?Ue(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Me,dx,dR,pR,gd,TZ,PZ,px=b(()=>{"use strict";Xr();Me={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},dx={[Me.PRE_TOOL_USE]:"pretooluse.mjs",[Me.POST_TOOL_USE]:"posttooluse.mjs",[Me.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Me.AGENT_SPAWN]:"agentspawn.mjs"},dR="@(?!context-mode/)",pR=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",dR],gd=pR.join("|"),TZ=[Me.PRE_TOOL_USE,Me.AGENT_SPAWN],PZ=[Me.POST_TOOL_USE,Me.USER_PROMPT_SUBMIT]});var gx={};Le(gx,{KiroAdapter:()=>yd});import{readFileSync as Cs,writeFileSync as mx,mkdirSync as fx}from"node:fs";import{resolve as On,dirname as hx}from"node:path";import{fileURLToPath as mR}from"node:url";import{homedir as Da}from"node:os";var yd,yx=b(()=>{"use strict";Ct();px();yd=class extends Se{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return On(Da(),".kiro","settings","mcp.json")}getConfigDir(e){return On(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Me.PRE_TOOL_USE]:[{matcher:gd,hooks:[{type:"command",command:Rs(Me.PRE_TOOL_USE,e)}]}],[Me.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Rs(Me.POST_TOOL_USE,e)}]}],[Me.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Rs(Me.AGENT_SPAWN,e)}]}],[Me.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Rs(Me.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Cs(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();fx(hx(r),{recursive:!0}),mx(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=On(Da(),".kiro","agents","default.json");try{let o=JSON.parse(Cs(n,"utf-8")).hooks??{};for(let i of[Me.PRE_TOOL_USE]){let c=(o[i]??[]).some(u=>Na(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Me.POST_TOOL_USE]){let c=(o[i]??[]).some(u=>Na(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=Cs(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=On(Da(),".kiro","extensions","context-mode","package.json");return JSON.parse(Cs(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=On(Da(),".kiro","agents"),s=On(n,"default.json");try{fx(n,{recursive:!0});let o={};try{o=JSON.parse(Cs(s,"utf-8"))}catch{}let i=o.hooks??{},a=[[Me.PRE_TOOL_USE,gd],[Me.POST_TOOL_USE,"*"],[Me.AGENT_SPAWN,"*"],[Me.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>Na(l,c))||(d.push({matcher:u,command:Rs(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${s}`))}o.hooks=i,mx(s,JSON.stringify(o,null,2),"utf-8")}catch(o){r.push(`Failed to configure hooks: ${o.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=On(hx(mR(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Cs(e,"utf-8")}catch{return`# context-mode
25
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function Da(t,e){let r=mx[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function Cs(t,e){let r=mx[t];return e&&r?Ue(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Me,mx,pR,mR,yd,AZ,NZ,fx=b(()=>{"use strict";Xr();Me={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},mx={[Me.PRE_TOOL_USE]:"pretooluse.mjs",[Me.POST_TOOL_USE]:"posttooluse.mjs",[Me.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Me.AGENT_SPAWN]:"agentspawn.mjs"},pR="@(?!context-mode/)",mR=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",pR],yd=mR.join("|"),AZ=[Me.PRE_TOOL_USE,Me.AGENT_SPAWN],NZ=[Me.POST_TOOL_USE,Me.USER_PROMPT_SUBMIT]});var _x={};Le(_x,{KiroAdapter:()=>_d});import{readFileSync as Os,writeFileSync as hx,mkdirSync as gx}from"node:fs";import{resolve as On,dirname as yx}from"node:path";import{fileURLToPath as fR}from"node:url";import{homedir as Ma}from"node:os";var _d,xx=b(()=>{"use strict";Ct();fx();_d=class extends Se{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return On(Ma(),".kiro","settings","mcp.json")}getConfigDir(e){return On(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Me.PRE_TOOL_USE]:[{matcher:yd,hooks:[{type:"command",command:Cs(Me.PRE_TOOL_USE,e)}]}],[Me.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Cs(Me.POST_TOOL_USE,e)}]}],[Me.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Cs(Me.AGENT_SPAWN,e)}]}],[Me.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Cs(Me.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Os(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();gx(yx(r),{recursive:!0}),hx(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=On(Ma(),".kiro","agents","default.json");try{let o=JSON.parse(Os(n,"utf-8")).hooks??{};for(let i of[Me.PRE_TOOL_USE]){let c=(o[i]??[]).some(u=>Da(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Me.POST_TOOL_USE]){let c=(o[i]??[]).some(u=>Da(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=Os(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=On(Ma(),".kiro","extensions","context-mode","package.json");return JSON.parse(Os(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=On(Ma(),".kiro","agents"),s=On(n,"default.json");try{gx(n,{recursive:!0});let o={};try{o=JSON.parse(Os(s,"utf-8"))}catch{}let i=o.hooks??{},a=[[Me.PRE_TOOL_USE,yd],[Me.POST_TOOL_USE,"*"],[Me.AGENT_SPAWN,"*"],[Me.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>Da(l,c))||(d.push({matcher:u,command:Cs(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${s}`))}o.hooks=i,hx(s,JSON.stringify(o,null,2),"utf-8")}catch(o){r.push(`Failed to configure hooks: ${o.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=On(yx(fR(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Os(e,"utf-8")}catch{return`# context-mode
26
26
 
27
- 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 vx={};Le(vx,{ZedAdapter:()=>xd});import{readFileSync as _d,writeFileSync as fR,mkdirSync as hR}from"node:fs";import{resolve as _x,dirname as xx}from"node:path";import{fileURLToPath as gR}from"node:url";import{homedir as yR}from"node:os";var xd,bx=b(()=>{"use strict";Ct();xd=class extends Se{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return _x(yR(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=_d(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();hR(xx(r),{recursive:!0}),fR(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=_d(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,s=e.includes("context-mode");return n&&s?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=_x(xx(gR(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return _d(e,"utf-8")}catch{return`# context-mode
27
+ 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 Sx={};Le(Sx,{ZedAdapter:()=>vd});import{readFileSync as xd,writeFileSync as hR,mkdirSync as gR}from"node:fs";import{resolve as vx,dirname as bx}from"node:path";import{fileURLToPath as yR}from"node:url";import{homedir as _R}from"node:os";var vd,kx=b(()=>{"use strict";Ct();vd=class extends Se{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return vx(_R(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=xd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();gR(bx(r),{recursive:!0}),hR(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=xd(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,s=e.includes("context-mode");return n&&s?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=vx(bx(yR(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return xd(e,"utf-8")}catch{return`# context-mode
28
28
 
29
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var vd,Sx=b(()=>{"use strict";vd="mcp__(?!.*context-mode)"});var Ex={};Le(Ex,{QwenCodeAdapter:()=>bd});import{readFileSync as _R,writeFileSync as xR,existsSync as vR}from"node:fs";import{resolve as kx,join as bR}from"node:path";import{homedir as wx}from"node:os";var bd,$x=b(()=>{"use strict";zl();Sx();Xr();bd=class extends ks{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 kx(wx(),".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",vd].join("|"),hooks:[{type:"command",command:Ue(`${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:Ue(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=_R(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){xR(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],s=this.readSettings()?.hooks??{};for(let o of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(s[o])&&s[o].length>0;r.push({check:`${o} hook`,status:i?"pass":"fail",message:i?`${o} hook configured in ~/.qwen/settings.json`:`${o} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${o} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,s]of Object.entries(r))if(Array.isArray(s)){for(let o of s)if(o.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(d=>{let p=d.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)"?/),_=h||g;return _?vR(_[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,s.push(`Removed ${u} stale ${i} hook(s)`))}let o=[{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",vd].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of o){let u={matcher:c,hooks:[{type:"command",command:Ue(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);l>=0?(d[l]=u,s.push(`Updated ${i} hook`)):(d.push(u),s.push(`Added ${i} hook`)),n[i]=d}else n[i]=[u],s.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:kx(bR(wx(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var Tx={};Le(Tx,{OMPAdapter:()=>wd});import{readFileSync as Sd,writeFileSync as SR,mkdirSync as kR}from"node:fs";import{resolve as kd,dirname as wR}from"node:path";import{homedir as ER}from"node:os";var wd,Px=b(()=>{"use strict";Ct();wd=class extends Se{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??kd(ER(),".omp","agent")}getSettingsPath(){return kd(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Sd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();kR(wR(r),{recursive:!0}),SR(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=Sd(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=kd(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(Sd(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
29
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var bd,wx=b(()=>{"use strict";bd="mcp__(?!.*context-mode)"});var Tx={};Le(Tx,{QwenCodeAdapter:()=>Sd});import{readFileSync as xR,writeFileSync as vR,existsSync as bR}from"node:fs";import{resolve as Ex,join as SR}from"node:path";import{homedir as $x}from"node:os";var Sd,Px=b(()=>{"use strict";Ll();wx();Xr();Sd=class extends ws{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 Ex($x(),".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",bd].join("|"),hooks:[{type:"command",command:Ue(`${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:Ue(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=xR(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){vR(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],s=this.readSettings()?.hooks??{};for(let o of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(s[o])&&s[o].length>0;r.push({check:`${o} hook`,status:i?"pass":"fail",message:i?`${o} hook configured in ~/.qwen/settings.json`:`${o} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${o} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,s]of Object.entries(r))if(Array.isArray(s)){for(let o of s)if(o.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(d=>{let p=d.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)"?/),_=h||g;return _?bR(_[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,s.push(`Removed ${u} stale ${i} hook(s)`))}let o=[{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",bd].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of o){let u={matcher:c,hooks:[{type:"command",command:Ue(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);l>=0?(d[l]=u,s.push(`Updated ${i} hook`)):(d.push(u),s.push(`Added ${i} hook`)),n[i]=d}else n[i]=[u],s.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:Ex(SR($x(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var Rx={};Le(Rx,{OMPAdapter:()=>Ed});import{readFileSync as kd,writeFileSync as kR,mkdirSync as wR}from"node:fs";import{resolve as wd,dirname as ER}from"node:path";import{homedir as $R}from"node:os";var Ed,Cx=b(()=>{"use strict";Ct();Ed=class extends Se{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??wd($R(),".omp","agent")}getSettingsPath(){return wd(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=kd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();wR(ER(r),{recursive:!0}),kR(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=kd(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=wd(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(kd(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
30
30
 
31
- 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 Rx={};Le(Rx,{PiAdapter:()=>Pd});import{readFileSync as Ed,writeFileSync as $R,mkdirSync as TR}from"node:fs";import{resolve as $d,dirname as PR}from"node:path";import{homedir as Td}from"node:os";var Pd,Cx=b(()=>{"use strict";Ct();Pd=class extends Se{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return $d(Td(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Ed(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();TR(PR(r),{recursive:!0}),$R(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=$d(Td(),".pi","extensions","context-mode","package.json");try{return JSON.parse(Ed(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=$d(Td(),".pi","extensions","context-mode","package.json");return JSON.parse(Ed(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
31
+ 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 Ox={};Le(Ox,{PiAdapter:()=>Rd});import{readFileSync as $d,writeFileSync as TR,mkdirSync as PR}from"node:fs";import{resolve as Td,dirname as RR}from"node:path";import{homedir as Pd}from"node:os";var Rd,Ix=b(()=>{"use strict";Ct();Rd=class extends Se{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Td(Pd(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=$d(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();PR(RR(r),{recursive:!0}),TR(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=Td(Pd(),".pi","extensions","context-mode","package.json");try{return JSON.parse($d(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=Td(Pd(),".pi","extensions","context-mode","package.json");return JSON.parse($d(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
32
32
 
33
- Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});var Ma={};Le(Ma,{PLATFORM_ENV_VARS:()=>Ix,__resetClaudeCodePluginCacheForTests:()=>OR,__seedClaudeCodePluginCacheMissForTests:()=>IR,detectPlatform:()=>sr,getAdapter:()=>jo,getSessionDirSegments:()=>Rd});import{existsSync as Ot,readFileSync as RR}from"node:fs";import{resolve as xt}from"node:path";import{homedir as Ox}from"node:os";function CR(){if(In!==null)return In!=="miss"&&In.hasCM;try{let t=xt(Ox(),".claude","plugins","installed_plugins.json"),e=RR(t,"utf-8"),r=JSON.parse(e),s=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(o=>o.includes("context-mode"));return In={hasCM:s},s}catch{return In="miss",!1}}function OR(){In=null}function IR(){In="miss"}function Rd(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function sr(t){if(t?.name){let n=y_[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,s]of Ix)if(s.some(o=>process.env[o]))return n==="vscode-copilot"&&CR()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${s.join(" or ")} env var set`};let r=Ox();return Ot(xt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ot(xt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ot(xt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ot(xt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ot(xt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ot(xt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ot(xt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ot(xt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ot(xt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ot(xt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ot(xt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ot(xt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ot(xt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function jo(t){let e=t??sr().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Bl(),Zl));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(C_(),R_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(N_(),A_));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(j_(),M_));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(Z_(),H_));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(G_(),W_));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(X_(),Y_));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(ax(),ix));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(lx(),ux));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(yx(),gx));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(bx(),vx));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>($x(),Ex));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(Px(),Tx));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Cx(),Rx));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Bl(),Zl));return new r}}}var In,Ix,Os=b(()=>{"use strict";__();In=null;Ix=[["claude-code",["CLAUDE_CODE_ENTRYPOINT","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CLAUDE_SESSION_ID"]],["antigravity",["ANTIGRAVITY_CLI_ALIAS"]],["cursor",["CURSOR_TRACE_ID","CURSOR_CLI"]],["kilo",["KILO","KILO_PID"]],["opencode",["OPENCODE","OPENCODE_PID"]],["zed",["ZED_SESSION_ID","ZED_TERM"]],["codex",["CODEX_THREAD_ID","CODEX_CI"]],["gemini-cli",["GEMINI_PROJECT_DIR","GEMINI_CLI"]],["vscode-copilot",["VSCODE_PID","VSCODE_CWD"]],["jetbrains-copilot",["IDEA_INITIAL_DIRECTORY"]],["qwen-code",["QWEN_PROJECT_DIR"]],["omp",["PI_CODING_AGENT_DIR"]],["pi",["PI_CONFIG_DIR","PI_SESSION_FILE","PI_COMPILED"]]]});var ie,Cd,M,vr,zo=b(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ie||(ie={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Cd||(Cd={}));M=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vr=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}}});var O,AR,vt,ja=b(()=>{zo();O=ie.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"]),AR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),vt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};vt.create=t=>new vt(t)});var NR,Ir,Od=b(()=>{ja();zo();NR=(t,e)=>{let r;switch(t.code){case O.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case O.invalid_union:r="Invalid input";break;case O.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case O.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:r="Invalid function arguments";break;case O.invalid_return_type:r="Invalid function return type";break;case O.invalid_date:r="Invalid date";break;case O.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case O.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case O.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case O.custom:r="Invalid input";break;case O.invalid_intersection_types:r="Intersection results could not be merged";break;case O.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},Ir=NR});function DR(t){Ax=t}function Is(){return Ax}var Ax,za=b(()=>{Od();Ax=Ir});function N(t,e){let r=Is(),n=Lo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ir?void 0:Ir].filter(s=>!!s)});t.common.issues.push(n)}var Lo,MR,Je,W,An,st,La,Fa,tn,As,Id=b(()=>{za();Od();Lo=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},MR=[];Je=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return W;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return W;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},W=Object.freeze({status:"aborted"}),An=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),La=t=>t.status==="aborted",Fa=t=>t.status==="dirty",tn=t=>t.status==="valid",As=t=>typeof Promise<"u"&&t instanceof Promise});var Nx=b(()=>{});var F,Dx=b(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(F||(F={}))});function Q(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function Lx(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function QR(t){return new RegExp(`^${Lx(t)}$`)}function Fx(t){let e=`${zx}T${Lx(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function eC(t,e){return!!((e==="v4"||!e)&&VR.test(t)||(e==="v6"||!e)&&GR.test(t))}function tC(t,e){if(!HR.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function rC(t,e){return!!((e==="v4"||!e)&&WR.test(t)||(e==="v6"||!e)&&KR.test(t))}function nC(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Ns(t){if(t instanceof St){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=bt.create(Ns(n))}return new St({...t._def,shape:()=>e})}else return t instanceof Dr?new Dr({...t._def,type:Ns(t.element)}):t instanceof bt?bt.create(Ns(t.unwrap())):t instanceof Sr?Sr.create(Ns(t.unwrap())):t instanceof br?br.create(t.items.map(e=>Ns(e))):t}function Nd(t,e){let r=vr(t),n=vr(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let s=ie.objectKeys(e),o=ie.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Nd(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Nd(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Ux(t,e){return new Bn({values:t,typeName:I.ZodEnum,...Q(e)})}function jx(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Hx(t,e={},r){return t?nn.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=jx(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=jx(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):nn.create()}var Zt,Mx,te,jR,zR,LR,FR,UR,HR,ZR,BR,qR,Ad,VR,WR,GR,KR,JR,YR,zx,XR,rn,Nn,Dn,Mn,jn,Ds,zn,Ln,nn,Nr,or,Ms,Dr,St,Fn,Ar,Ua,Un,br,Ha,js,zs,Za,Hn,Zn,Bn,qn,sn,Bt,bt,Sr,Vn,Wn,Ls,sC,Fo,Uo,Gn,oC,I,iC,Zx,Bx,aC,cC,qx,uC,lC,dC,pC,mC,fC,hC,gC,yC,Dd,_C,xC,vC,bC,SC,kC,wC,EC,$C,TC,PC,RC,CC,OC,IC,AC,NC,DC,MC,jC,zC,LC,FC,UC,Vx=b(()=>{ja();za();Dx();Id();zo();Zt=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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}},Mx=(t,e)=>{if(tn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new vt(t.common.issues);return this._error=r,this._error}}};te=class{get description(){return this._def.description}_getType(e){return vr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:vr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Je,ctx:{common:e.parent.common,data:e.data,parsedType:vr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(As(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Mx(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return tn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>tn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(As(s)?s:Promise.resolve(s));return Mx(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:O.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Bt({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return bt.create(this,this._def)}nullable(){return Sr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Dr.create(this)}promise(){return sn.create(this,this._def)}or(e){return Fn.create([this,e],this._def)}and(e){return Un.create(this,e,this._def)}transform(e){return new Bt({...Q(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Vn({...Q(this._def),innerType:this,defaultValue:r,typeName:I.ZodDefault})}brand(){return new Fo({typeName:I.ZodBranded,type:this,...Q(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Wn({...Q(this._def),innerType:this,catchValue:r,typeName:I.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Uo.create(this,e)}readonly(){return Gn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jR=/^c[^\s-]{8,}$/i,zR=/^[0-9a-z]+$/,LR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,FR=/^[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,UR=/^[a-z0-9_-]{21}$/i,HR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ZR=/^[-+]?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)?)??$/,BR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,qR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",VR=/^(?:(?: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])$/,WR=/^(?:(?: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])$/,GR=/^(([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]))$/,KR=/^(([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])$/,JR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,YR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zx="((\\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])))",XR=new RegExp(`^${zx}$`);rn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:M.string,received:o.parsedType}),W}let n=new Je,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?N(s,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&N(s,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")BR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"email",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Ad||(Ad=new RegExp(qR,"u")),Ad.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"emoji",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")FR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"uuid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")UR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"nanoid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")jR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")zR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid2",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")LR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ulid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),N(s,{validation:"url",code:O.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"regex",code:O.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Fx(o).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?XR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?QR(o).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?ZR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?eC(e.data,o.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ip",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?tC(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"jwt",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?rC(e.data,o.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cidr",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?JR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?YR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64url",code:O.invalid_string,message:o.message}),n.dirty()):ie.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:O.invalid_string,...F.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.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,...F.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,...F.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...F.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...F.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...F.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...F.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...F.errToObj(r)})}nonempty(e){return this.min(1,F.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};rn.create=t=>new rn({checks:[],typeName:I.ZodString,coerce:t?.coerce??!1,...Q(t)});Nn=class t extends te{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)!==M.number){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:M.number,received:o.parsedType}),W}let n,s=new Je;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?nC(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_finite,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,F.toString(r))}gt(e,r){return this.setLimit("min",e,!1,F.toString(r))}lte(e,r){return this.setLimit("max",e,!0,F.toString(r))}lt(e,r){return this.setLimit("max",e,!1,F.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Nn.create=t=>new Nn({checks:[],typeName:I.ZodNumber,coerce:t?.coerce||!1,...Q(t)});Dn=class t extends te{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)!==M.bigint)return this._getInvalidInput(e);let n,s=new Je;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:M.bigint,received:r.parsedType}),W}gte(e,r){return this.setLimit("min",e,!0,F.toString(r))}gt(e,r){return this.setLimit("min",e,!1,F.toString(r))}lte(e,r){return this.setLimit("max",e,!0,F.toString(r))}lt(e,r){return this.setLimit("max",e,!1,F.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:F.toString(s)}]})}_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:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Dn.create=t=>new Dn({checks:[],typeName:I.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});Mn=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.boolean,received:n.parsedType}),W}return st(e.data)}};Mn.create=t=>new Mn({typeName:I.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});jn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:M.date,received:o.parsedType}),W}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_date}),W}let n=new Je,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ie.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:F.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:F.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};jn.create=t=>new jn({checks:[],coerce:t?.coerce||!1,typeName:I.ZodDate,...Q(t)});Ds=class extends te{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.symbol,received:n.parsedType}),W}return st(e.data)}};Ds.create=t=>new Ds({typeName:I.ZodSymbol,...Q(t)});zn=class extends te{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.undefined,received:n.parsedType}),W}return st(e.data)}};zn.create=t=>new zn({typeName:I.ZodUndefined,...Q(t)});Ln=class extends te{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.null,received:n.parsedType}),W}return st(e.data)}};Ln.create=t=>new Ln({typeName:I.ZodNull,...Q(t)});nn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};nn.create=t=>new nn({typeName:I.ZodAny,...Q(t)});Nr=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};Nr.create=t=>new Nr({typeName:I.ZodUnknown,...Q(t)});or=class extends te{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:M.never,received:r.parsedType}),W}};or.create=t=>new or({typeName:I.ZodNever,...Q(t)});Ms=class extends te{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.void,received:n.parsedType}),W}return st(e.data)}};Ms.create=t=>new Ms({typeName:I.ZodVoid,...Q(t)});Dr=class t extends te{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return N(r,{code:O.invalid_type,expected:M.array,received:r.parsedType}),W;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(N(r,{code:i?O.too_big:O.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(N(r,{code:O.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(N(r,{code:O.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Zt(r,i,r.path,a)))).then(i=>Je.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Zt(r,i,r.path,a)));return Je.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:F.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:F.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:F.toString(r)}})}nonempty(e){return this.min(1,e)}};Dr.create=(t,e)=>new Dr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...Q(e)});St=class t extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){let u=this._getOrReturnCtx(e);return N(u,{code:O.invalid_type,expected:M.object,received:u.parsedType}),W}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof or&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=o[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Zt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof or){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")a.length>0&&(N(s,{code:O.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Zt(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>Je.mergeObjectSync(n,u)):Je.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return F.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:F.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:I.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ie.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ie.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Ns(this)}partial(e){let r={};for(let n of ie.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ie.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof bt;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return Ux(ie.objectKeys(this.shape))}};St.create=(t,e)=>new St({shape:()=>t,unknownKeys:"strip",catchall:or.create(),typeName:I.ZodObject,...Q(e)});St.strictCreate=(t,e)=>new St({shape:()=>t,unknownKeys:"strict",catchall:or.create(),typeName:I.ZodObject,...Q(e)});St.lazycreate=(t,e)=>new St({shape:t,unknownKeys:"strip",catchall:or.create(),typeName:I.ZodObject,...Q(e)});Fn=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new vt(a.ctx.common.issues));return N(r,{code:O.invalid_union,unionErrors:i}),W}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new vt(c));return N(r,{code:O.invalid_union,unionErrors:a}),W}}get options(){return this._def.options}};Fn.create=(t,e)=>new Fn({options:t,typeName:I.ZodUnion,...Q(e)});Ar=t=>t instanceof Hn?Ar(t.schema):t instanceof Bt?Ar(t.innerType()):t instanceof Zn?[t.value]:t instanceof Bn?t.options:t instanceof qn?ie.objectValues(t.enum):t instanceof Vn?Ar(t._def.innerType):t instanceof zn?[void 0]:t instanceof Ln?[null]:t instanceof bt?[void 0,...Ar(t.unwrap())]:t instanceof Sr?[null,...Ar(t.unwrap())]:t instanceof Fo||t instanceof Gn?Ar(t.unwrap()):t instanceof Wn?Ar(t._def.innerType):[],Ua=class t extends te{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return N(r,{code:O.invalid_type,expected:M.object,received:r.parsedType}),W;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(N(r,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Ar(o.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(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:I.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Q(n)})}};Un=class extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(La(o)||La(i))return W;let a=Nd(o.value,i.value);return a.valid?((Fa(o)||Fa(i))&&r.dirty(),{status:r.value,value:a.data}):(N(n,{code:O.invalid_intersection_types}),W)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Un.create=(t,e,r)=>new Un({left:t,right:e,typeName:I.ZodIntersection,...Q(r)});br=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return N(n,{code:O.invalid_type,expected:M.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return N(n,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&n.data.length>this._def.items.length&&(N(n,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Zt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Je.mergeArray(r,i)):Je.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};br.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new br({items:t,typeName:I.ZodTuple,rest:null,...Q(e)})};Ha=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return N(n,{code:O.invalid_type,expected:M.object,received:n.parsedType}),W;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Zt(n,a,n.path,a)),value:i._parse(new Zt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Je.mergeObjectAsync(r,s):Je.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof te?new t({keyType:e,valueType:r,typeName:I.ZodRecord,...Q(n)}):new t({keyType:rn.create(),valueType:e,typeName:I.ZodRecord,...Q(r)})}},js=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return N(n,{code:O.invalid_type,expected:M.map,received:n.parsedType}),W;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Zt(n,a,n.path,[u,"key"])),value:o._parse(new Zt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};js.create=(t,e,r)=>new js({valueType:e,keyType:t,typeName:I.ZodMap,...Q(r)});zs=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return N(n,{code:O.invalid_type,expected:M.set,received:n.parsedType}),W;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(N(n,{code:O.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(N(n,{code:O.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return W;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Zt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:F.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:F.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};zs.create=(t,e)=>new zs({valueType:t,minSize:null,maxSize:null,typeName:I.ZodSet,...Q(e)});Za=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return N(r,{code:O.invalid_type,expected:M.function,received:r.parsedType}),W;function n(a,c){return Lo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Is(),Ir].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:c}})}function s(a,c){return Lo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Is(),Ir].filter(u=>!!u),issueData:{code:O.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof sn){let a=this;return st(async function(...c){let u=new vt([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(s(l,f)),u})})}else{let a=this;return st(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new vt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new vt([s(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:br.create(e).rest(Nr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||br.create([]).rest(Nr.create()),returns:r||Nr.create(),typeName:I.ZodFunction,...Q(n)})}},Hn=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Hn.create=(t,e)=>new Hn({getter:t,typeName:I.ZodLazy,...Q(e)});Zn=class extends te{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return N(r,{received:r.data,code:O.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zn.create=(t,e)=>new Zn({value:t,typeName:I.ZodLiteral,...Q(e)});Bn=class t extends te{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ie.joinValues(n),received:r.parsedType,code:O.invalid_type}),W}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{received:r.data,code:O.invalid_enum_value,options:n}),W}return st(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Bn.create=Ux;qn=class extends te{_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let s=ie.objectValues(r);return N(n,{expected:ie.joinValues(s),received:n.parsedType,code:O.invalid_type}),W}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ie.objectValues(r);return N(n,{received:n.data,code:O.invalid_enum_value,options:s}),W}return st(e.data)}get enum(){return this._def.values}};qn.create=(t,e)=>new qn({values:t,typeName:I.ZodNativeEnum,...Q(e)});sn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return N(r,{code:O.invalid_type,expected:M.promise,received:r.parsedType}),W;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return st(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};sn.create=(t,e)=>new sn({type:t,typeName:I.ZodPromise,...Q(e)});Bt=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{N(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return W;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?W:c.status==="dirty"?An(c.value):r.value==="dirty"?An(c.value):c});{if(r.value==="aborted")return W;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?W:a.status==="dirty"?An(a.value):r.value==="dirty"?An(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?W:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?W:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!tn(i))return W;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>tn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):W);ie.assertNever(s)}};Bt.create=(t,e,r)=>new Bt({schema:t,typeName:I.ZodEffects,effect:e,...Q(r)});Bt.createWithPreprocess=(t,e,r)=>new Bt({schema:e,effect:{type:"preprocess",transform:t},typeName:I.ZodEffects,...Q(r)});bt=class extends te{_parse(e){return this._getType(e)===M.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bt.create=(t,e)=>new bt({innerType:t,typeName:I.ZodOptional,...Q(e)});Sr=class extends te{_parse(e){return this._getType(e)===M.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Sr.create=(t,e)=>new Sr({innerType:t,typeName:I.ZodNullable,...Q(e)});Vn=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Vn.create=(t,e)=>new Vn({innerType:t,typeName:I.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});Wn=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return As(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Wn.create=(t,e)=>new Wn({innerType:t,typeName:I.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Ls=class extends te{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.nan,received:n.parsedType}),W}return{status:"valid",value:e.data}}};Ls.create=t=>new Ls({typeName:I.ZodNaN,...Q(t)});sC=Symbol("zod_brand"),Fo=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Uo=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?W:o.status==="dirty"?(r.dirty(),An(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?W:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:I.ZodPipeline})}},Gn=class extends te{_parse(e){let r=this._def.innerType._parse(e),n=s=>(tn(s)&&(s.value=Object.freeze(s.value)),s);return As(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Gn.create=(t,e)=>new Gn({innerType:t,typeName:I.ZodReadonly,...Q(e)});oC={object:St.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(I||(I={}));iC=(t,e={message:`Input not instance of ${t.name}`})=>Hx(r=>r instanceof t,e),Zx=rn.create,Bx=Nn.create,aC=Ls.create,cC=Dn.create,qx=Mn.create,uC=jn.create,lC=Ds.create,dC=zn.create,pC=Ln.create,mC=nn.create,fC=Nr.create,hC=or.create,gC=Ms.create,yC=Dr.create,Dd=St.create,_C=St.strictCreate,xC=Fn.create,vC=Ua.create,bC=Un.create,SC=br.create,kC=Ha.create,wC=js.create,EC=zs.create,$C=Za.create,TC=Hn.create,PC=Zn.create,RC=Bn.create,CC=qn.create,OC=sn.create,IC=Bt.create,AC=bt.create,NC=Sr.create,DC=Bt.createWithPreprocess,MC=Uo.create,jC=()=>Zx().optional(),zC=()=>Bx().optional(),LC=()=>qx().optional(),FC={string:(t=>rn.create({...t,coerce:!0})),number:(t=>Nn.create({...t,coerce:!0})),boolean:(t=>Mn.create({...t,coerce:!0})),bigint:(t=>Dn.create({...t,coerce:!0})),date:(t=>jn.create({...t,coerce:!0}))},UC=W});var U={};Le(U,{BRAND:()=>sC,DIRTY:()=>An,EMPTY_PATH:()=>MR,INVALID:()=>W,NEVER:()=>UC,OK:()=>st,ParseStatus:()=>Je,Schema:()=>te,ZodAny:()=>nn,ZodArray:()=>Dr,ZodBigInt:()=>Dn,ZodBoolean:()=>Mn,ZodBranded:()=>Fo,ZodCatch:()=>Wn,ZodDate:()=>jn,ZodDefault:()=>Vn,ZodDiscriminatedUnion:()=>Ua,ZodEffects:()=>Bt,ZodEnum:()=>Bn,ZodError:()=>vt,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>Za,ZodIntersection:()=>Un,ZodIssueCode:()=>O,ZodLazy:()=>Hn,ZodLiteral:()=>Zn,ZodMap:()=>js,ZodNaN:()=>Ls,ZodNativeEnum:()=>qn,ZodNever:()=>or,ZodNull:()=>Ln,ZodNullable:()=>Sr,ZodNumber:()=>Nn,ZodObject:()=>St,ZodOptional:()=>bt,ZodParsedType:()=>M,ZodPipeline:()=>Uo,ZodPromise:()=>sn,ZodReadonly:()=>Gn,ZodRecord:()=>Ha,ZodSchema:()=>te,ZodSet:()=>zs,ZodString:()=>rn,ZodSymbol:()=>Ds,ZodTransformer:()=>Bt,ZodTuple:()=>br,ZodType:()=>te,ZodUndefined:()=>zn,ZodUnion:()=>Fn,ZodUnknown:()=>Nr,ZodVoid:()=>Ms,addIssueToContext:()=>N,any:()=>mC,array:()=>yC,bigint:()=>cC,boolean:()=>qx,coerce:()=>FC,custom:()=>Hx,date:()=>uC,datetimeRegex:()=>Fx,defaultErrorMap:()=>Ir,discriminatedUnion:()=>vC,effect:()=>IC,enum:()=>RC,function:()=>$C,getErrorMap:()=>Is,getParsedType:()=>vr,instanceof:()=>iC,intersection:()=>bC,isAborted:()=>La,isAsync:()=>As,isDirty:()=>Fa,isValid:()=>tn,late:()=>oC,lazy:()=>TC,literal:()=>PC,makeIssue:()=>Lo,map:()=>wC,nan:()=>aC,nativeEnum:()=>CC,never:()=>hC,null:()=>pC,nullable:()=>NC,number:()=>Bx,object:()=>Dd,objectUtil:()=>Cd,oboolean:()=>LC,onumber:()=>zC,optional:()=>AC,ostring:()=>jC,pipeline:()=>MC,preprocess:()=>DC,promise:()=>OC,quotelessJson:()=>AR,record:()=>kC,set:()=>EC,setErrorMap:()=>DR,strictObject:()=>_C,string:()=>Zx,symbol:()=>lC,transformer:()=>IC,tuple:()=>SC,undefined:()=>dC,union:()=>xC,unknown:()=>fC,util:()=>ie,void:()=>gC});var Ba=b(()=>{za();Id();Nx();zo();Vx();ja()});var Ho=b(()=>{Ba()});function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let u=r?.Parent?new o:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function It(t){return t&&Object.assign(qa,t),qa}var ZC,Mr,qa,Fs=b(()=>{ZC=Object.freeze({status:"aborted"});Mr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},qa={}});var ce={};Le(ce,{BIGINT_FORMAT_RANGES:()=>Gx,Class:()=>jd,NUMBER_FORMAT_RANGES:()=>Bd,aborted:()=>Jn,allowsEval:()=>Ud,assert:()=>GC,assertEqual:()=>BC,assertIs:()=>VC,assertNever:()=>WC,assertNotEqual:()=>qC,assignProp:()=>Fd,cached:()=>qo,captureStackTrace:()=>Wa,cleanEnum:()=>aO,cleanRegex:()=>Wo,clone:()=>At,createTransparentProxy:()=>eO,defineLazy:()=>ke,esc:()=>Kn,escapeRegex:()=>on,extend:()=>nO,finalizeIssue:()=>ir,floatSafeRemainder:()=>Ld,getElementAtPath:()=>KC,getEnumValues:()=>Bo,getLengthableOrigin:()=>Go,getParsedType:()=>QC,getSizableOrigin:()=>Kx,isObject:()=>Us,isPlainObject:()=>Hs,issue:()=>qd,joinValues:()=>Va,jsonStringifyReplacer:()=>zd,merge:()=>sO,normalizeParams:()=>G,nullish:()=>Vo,numKeys:()=>XC,omit:()=>rO,optionalKeys:()=>Zd,partial:()=>oO,pick:()=>tO,prefixIssues:()=>kr,primitiveTypes:()=>Wx,promiseAllObject:()=>JC,propertyKeyTypes:()=>Hd,randomString:()=>YC,required:()=>iO,stringifyPrimitive:()=>Ga,unwrapMessage:()=>Zo});function BC(t){return t}function qC(t){return t}function VC(t){}function WC(t){throw new Error}function GC(t){}function Bo(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function Va(t,e="|"){return t.map(r=>Ga(r)).join(e)}function zd(t,e){return typeof e=="bigint"?e.toString():e}function qo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Vo(t){return t==null}function Wo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ld(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ke(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function Fd(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function KC(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function JC(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=n[o];return s})}function YC(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Kn(t){return JSON.stringify(t)}function Us(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hs(t){if(Us(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Us(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function XC(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function on(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function At(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function G(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function eO(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,o){return e??(e=t()),Reflect.set(e,n,s,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function Ga(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Zd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function tO(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return At(t,{...t._zod.def,shape:r,checks:[]})}function rO(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return At(t,{...t._zod.def,shape:r,checks:[]})}function nO(t,e){if(!Hs(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Fd(this,"shape",n),n},checks:[]};return At(t,r)}function sO(t,e){return At(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Fd(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function oO(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return At(e,{...e._zod.def,shape:s,checks:[]})}function iO(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(let o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return At(e,{...e._zod.def,shape:s,checks:[]})}function Jn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function kr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Zo(t){return typeof t=="string"?t:t?.message}function ir(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=Zo(t.inst?._zod.def?.error?.(t))??Zo(e?.error?.(t))??Zo(r.customError?.(t))??Zo(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Kx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Go(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function qd(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function aO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Wa,Ud,QC,Hd,Wx,Bd,Gx,jd,wr=b(()=>{Wa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Ud=qo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});QC=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}`)}},Hd=new Set(["string","number","symbol"]),Wx=new Set(["string","number","bigint","boolean","symbol","undefined"]);Bd={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]},Gx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};jd=class{constructor(...e){}}});function Vd(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function Wd(t,e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>s({issues:a}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(t),n}var Jx,Ka,Ko,Gd=b(()=>{Fs();wr();Jx=(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,zd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ka=w("$ZodError",Jx),Ko=w("$ZodError",Jx,{Parent:Error})});var Kd,Jd,Yd,Xd,Qd,Yn,ep,Xn,tp=b(()=>{Fs();Gd();wr();Kd=t=>(e,r,n,s)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Mr;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>ir(c,o,It())));throw Wa(a,s?.callee),a}return i.value},Jd=Kd(Ko),Yd=t=>async(e,r,n,s)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>ir(c,o,It())));throw Wa(a,s?.callee),a}return i.value},Xd=Yd(Ko),Qd=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Mr;return o.issues.length?{success:!1,error:new(t??Ka)(o.issues.map(i=>ir(i,s,It())))}:{success:!0,data:o.value}},Yn=Qd(Ko),ep=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>ir(i,s,It())))}:{success:!0,data:o.value}},Xn=ep(Ko)});function iv(){return new RegExp(uO,"u")}function gv(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 yv(t){return new RegExp(`^${gv(t)}$`)}function _v(t){let e=gv({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${fv}T(?:${n})$`)}var Yx,Xx,Qx,ev,tv,rv,nv,sv,rp,ov,uO,av,cv,uv,lv,dv,np,pv,mv,fv,hv,xv,vv,bv,Sv,kv,wv,Ev,Ya=b(()=>{Yx=/^[cC][^\s-]{8,}$/,Xx=/^[0-9a-z]+$/,Qx=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ev=/^[0-9a-vA-V]{20}$/,tv=/^[A-Za-z0-9]{27}$/,rv=/^[a-zA-Z0-9_-]{21}$/,nv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sv=/^([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})$/,rp=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)$/,ov=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";av=/^(?:(?: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])$/,cv=/^(([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})$/,uv=/^((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])$/,lv=/^(([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])$/,dv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,np=/^[A-Za-z0-9_-]*$/,pv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,mv=/^\+(?:[0-9]){6,14}[0-9]$/,fv="(?:(?:\\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])))",hv=new RegExp(`^${fv}$`);xv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},vv=/^\d+$/,bv=/^-?\d+(?:\.\d+)?/i,Sv=/true|false/i,kv=/null/i,wv=/^[^A-Z]*$/,Ev=/^[^a-z]*$/});var Ye,$v,sp,op,Tv,Pv,Rv,Cv,Ov,Jo,Iv,Av,Nv,Dv,Mv,jv,zv,Xa=b(()=>{Fs();Ya();wr();Ye=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),$v={number:"number",bigint:"bigint",object:"date"},sp=w("$ZodCheckLessThan",(t,e)=>{Ye.init(t,e);let r=$v[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),op=w("$ZodCheckGreaterThan",(t,e)=>{Ye.init(t,e);let r=$v[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Tv=w("$ZodCheckMultipleOf",(t,e)=>{Ye.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Ld(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Pv=w("$ZodCheckNumberFormat",(t,e)=>{Ye.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Bd[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,r&&(a.pattern=vv)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}}),Rv=w("$ZodCheckMaxLength",(t,e)=>{var r;Ye.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Vo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let i=Go(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Cv=w("$ZodCheckMinLength",(t,e)=>{var r;Ye.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Vo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let i=Go(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Ov=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ye.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Vo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,o=s.length;if(o===e.length)return;let i=Go(s),a=o>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Jo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ye.init(t,e),t._zod.onattach.push(s=>{let o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Iv=w("$ZodCheckRegex",(t,e)=>{Jo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Av=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=wv),Jo.init(t,e)}),Nv=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ev),Jo.init(t,e)}),Dv=w("$ZodCheckIncludes",(t,e)=>{Ye.init(t,e);let r=on(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),Mv=w("$ZodCheckStartsWith",(t,e)=>{Ye.init(t,e);let r=new RegExp(`^${on(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),jv=w("$ZodCheckEndsWith",(t,e)=>{Ye.init(t,e);let r=new RegExp(`.*${on(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),zv=w("$ZodCheckOverwrite",(t,e)=>{Ye.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Qa,ip=b(()=>{Qa=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
33
+ Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});var ja={};Le(ja,{PLATFORM_ENV_VARS:()=>jo,__resetClaudeCodePluginCacheForTests:()=>IR,__seedClaudeCodePluginCacheMissForTests:()=>AR,detectPlatform:()=>sr,foreignWorkspaceEnv:()=>MR,getAdapter:()=>zo,getEnvVarNames:()=>DR,getSessionDirSegments:()=>Od,workspaceEnvVarsFor:()=>Cd});import{existsSync as Ot,readFileSync as CR}from"node:fs";import{resolve as xt}from"node:path";import{homedir as Ax}from"node:os";function OR(){if(In!==null)return In!=="miss"&&In.hasCM;try{let t=xt(Ax(),".claude","plugins","installed_plugins.json"),e=CR(t,"utf-8"),r=JSON.parse(e),s=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(o=>o.includes("context-mode"));return In={hasCM:s},s}catch{return In="miss",!1}}function IR(){In=null}function AR(){In="miss"}function DR(t){return(jo.get(t)??[]).map(e=>e.name)}function Cd(t){return(jo.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function MR(t){let e=new Set;for(let[r,n]of jo)if(r!==t)for(let s of n)s.role==="workspace"&&e.add(s.name);return e}function Od(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function sr(t){if(t?.name){let n=x_[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,s]of jo)if(s.some(o=>o.detect!==!1&&process.env[o.name]))return n==="vscode-copilot"&&OR()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${s.filter(o=>o.detect!==!1).map(o=>o.name).join(" or ")} env var set`};let r=Ax();return Ot(xt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ot(xt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ot(xt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ot(xt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ot(xt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ot(xt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ot(xt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ot(xt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ot(xt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ot(xt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ot(xt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ot(xt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ot(xt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function zo(t){let e=t??sr().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(ql(),Bl));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(I_(),O_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(M_(),D_));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(L_(),z_));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(q_(),B_));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(J_(),K_));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(ex(),Q_));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(ux(),cx));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(px(),dx));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(xx(),_x));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(kx(),Sx));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(Px(),Tx));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(Cx(),Rx));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Ix(),Ox));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(ql(),Bl));return new r}}}var In,NR,jo,An=b(()=>{"use strict";v_();In=null;NR=[["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",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"}]]],jo=new Map(NR)});var ie,Id,M,vr,Lo=b(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ie||(ie={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Id||(Id={}));M=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vr=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}}});var O,jR,vt,za=b(()=>{Lo();O=ie.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"]),jR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),vt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};vt.create=t=>new vt(t)});var zR,Ir,Ad=b(()=>{za();Lo();zR=(t,e)=>{let r;switch(t.code){case O.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case O.invalid_union:r="Invalid input";break;case O.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case O.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:r="Invalid function arguments";break;case O.invalid_return_type:r="Invalid function return type";break;case O.invalid_date:r="Invalid date";break;case O.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case O.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case O.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case O.custom:r="Invalid input";break;case O.invalid_intersection_types:r="Intersection results could not be merged";break;case O.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},Ir=zR});function LR(t){Nx=t}function Is(){return Nx}var Nx,La=b(()=>{Ad();Nx=Ir});function N(t,e){let r=Is(),n=Fo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ir?void 0:Ir].filter(s=>!!s)});t.common.issues.push(n)}var Fo,FR,Je,W,Nn,st,Fa,Ua,tn,As,Nd=b(()=>{La();Ad();Fo=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},FR=[];Je=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return W;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return W;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},W=Object.freeze({status:"aborted"}),Nn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),Fa=t=>t.status==="aborted",Ua=t=>t.status==="dirty",tn=t=>t.status==="valid",As=t=>typeof Promise<"u"&&t instanceof Promise});var Dx=b(()=>{});var F,Mx=b(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(F||(F={}))});function Q(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function Fx(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function nC(t){return new RegExp(`^${Fx(t)}$`)}function Ux(t){let e=`${Lx}T${Fx(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function sC(t,e){return!!((e==="v4"||!e)&&JR.test(t)||(e==="v6"||!e)&&XR.test(t))}function oC(t,e){if(!VR.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function iC(t,e){return!!((e==="v4"||!e)&&YR.test(t)||(e==="v6"||!e)&&QR.test(t))}function aC(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Ns(t){if(t instanceof St){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=bt.create(Ns(n))}return new St({...t._def,shape:()=>e})}else return t instanceof Dr?new Dr({...t._def,type:Ns(t.element)}):t instanceof bt?bt.create(Ns(t.unwrap())):t instanceof Sr?Sr.create(Ns(t.unwrap())):t instanceof br?br.create(t.items.map(e=>Ns(e))):t}function Md(t,e){let r=vr(t),n=vr(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let s=ie.objectKeys(e),o=ie.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Md(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Md(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Hx(t,e){return new qn({values:t,typeName:I.ZodEnum,...Q(e)})}function zx(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Zx(t,e={},r){return t?nn.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=zx(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=zx(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):nn.create()}var Zt,jx,te,UR,HR,ZR,BR,qR,VR,WR,GR,KR,Dd,JR,YR,XR,QR,eC,tC,Lx,rC,rn,Dn,Mn,jn,zn,Ds,Ln,Fn,nn,Nr,or,Ms,Dr,St,Un,Ar,Ha,Hn,br,Za,js,zs,Ba,Zn,Bn,qn,Vn,sn,Bt,bt,Sr,Wn,Gn,Ls,cC,Uo,Ho,Kn,uC,I,lC,Bx,qx,dC,pC,Vx,mC,fC,hC,gC,yC,_C,xC,vC,bC,jd,SC,kC,wC,EC,$C,TC,PC,RC,CC,OC,IC,AC,NC,DC,MC,jC,zC,LC,FC,UC,HC,ZC,BC,qC,Wx=b(()=>{za();La();Mx();Nd();Lo();Zt=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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}},jx=(t,e)=>{if(tn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new vt(t.common.issues);return this._error=r,this._error}}};te=class{get description(){return this._def.description}_getType(e){return vr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:vr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Je,ctx:{common:e.parent.common,data:e.data,parsedType:vr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(As(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return jx(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return tn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>tn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(As(s)?s:Promise.resolve(s));return jx(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:O.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Bt({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return bt.create(this,this._def)}nullable(){return Sr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Dr.create(this)}promise(){return sn.create(this,this._def)}or(e){return Un.create([this,e],this._def)}and(e){return Hn.create(this,e,this._def)}transform(e){return new Bt({...Q(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Wn({...Q(this._def),innerType:this,defaultValue:r,typeName:I.ZodDefault})}brand(){return new Uo({typeName:I.ZodBranded,type:this,...Q(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Gn({...Q(this._def),innerType:this,catchValue:r,typeName:I.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ho.create(this,e)}readonly(){return Kn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},UR=/^c[^\s-]{8,}$/i,HR=/^[0-9a-z]+$/,ZR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,BR=/^[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,qR=/^[a-z0-9_-]{21}$/i,VR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,WR=/^[-+]?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)?)??$/,GR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,KR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",JR=/^(?:(?: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])$/,YR=/^(?:(?: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])$/,XR=/^(([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]))$/,QR=/^(([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])$/,eC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Lx="((\\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])))",rC=new RegExp(`^${Lx}$`);rn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:M.string,received:o.parsedType}),W}let n=new Je,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?N(s,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&N(s,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")GR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"email",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Dd||(Dd=new RegExp(KR,"u")),Dd.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"emoji",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")BR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"uuid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")qR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"nanoid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")UR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")HR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid2",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ZR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ulid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),N(s,{validation:"url",code:O.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"regex",code:O.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Ux(o).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?rC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?nC(o).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?WR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?sC(e.data,o.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ip",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?oC(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"jwt",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?iC(e.data,o.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cidr",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?eC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?tC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64url",code:O.invalid_string,message:o.message}),n.dirty()):ie.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:O.invalid_string,...F.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.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,...F.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,...F.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...F.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...F.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...F.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...F.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...F.errToObj(r)})}nonempty(e){return this.min(1,F.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};rn.create=t=>new rn({checks:[],typeName:I.ZodString,coerce:t?.coerce??!1,...Q(t)});Dn=class t extends te{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)!==M.number){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:M.number,received:o.parsedType}),W}let n,s=new Je;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?aC(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_finite,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,F.toString(r))}gt(e,r){return this.setLimit("min",e,!1,F.toString(r))}lte(e,r){return this.setLimit("max",e,!0,F.toString(r))}lt(e,r){return this.setLimit("max",e,!1,F.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Dn.create=t=>new Dn({checks:[],typeName:I.ZodNumber,coerce:t?.coerce||!1,...Q(t)});Mn=class t extends te{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)!==M.bigint)return this._getInvalidInput(e);let n,s=new Je;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:M.bigint,received:r.parsedType}),W}gte(e,r){return this.setLimit("min",e,!0,F.toString(r))}gt(e,r){return this.setLimit("min",e,!1,F.toString(r))}lte(e,r){return this.setLimit("max",e,!0,F.toString(r))}lt(e,r){return this.setLimit("max",e,!1,F.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:F.toString(s)}]})}_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:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Mn.create=t=>new Mn({checks:[],typeName:I.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});jn=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.boolean,received:n.parsedType}),W}return st(e.data)}};jn.create=t=>new jn({typeName:I.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});zn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:M.date,received:o.parsedType}),W}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_date}),W}let n=new Je,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:O.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ie.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:F.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:F.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};zn.create=t=>new zn({checks:[],coerce:t?.coerce||!1,typeName:I.ZodDate,...Q(t)});Ds=class extends te{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.symbol,received:n.parsedType}),W}return st(e.data)}};Ds.create=t=>new Ds({typeName:I.ZodSymbol,...Q(t)});Ln=class extends te{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.undefined,received:n.parsedType}),W}return st(e.data)}};Ln.create=t=>new Ln({typeName:I.ZodUndefined,...Q(t)});Fn=class extends te{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.null,received:n.parsedType}),W}return st(e.data)}};Fn.create=t=>new Fn({typeName:I.ZodNull,...Q(t)});nn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};nn.create=t=>new nn({typeName:I.ZodAny,...Q(t)});Nr=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};Nr.create=t=>new Nr({typeName:I.ZodUnknown,...Q(t)});or=class extends te{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:M.never,received:r.parsedType}),W}};or.create=t=>new or({typeName:I.ZodNever,...Q(t)});Ms=class extends te{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.void,received:n.parsedType}),W}return st(e.data)}};Ms.create=t=>new Ms({typeName:I.ZodVoid,...Q(t)});Dr=class t extends te{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return N(r,{code:O.invalid_type,expected:M.array,received:r.parsedType}),W;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(N(r,{code:i?O.too_big:O.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(N(r,{code:O.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(N(r,{code:O.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Zt(r,i,r.path,a)))).then(i=>Je.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Zt(r,i,r.path,a)));return Je.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:F.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:F.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:F.toString(r)}})}nonempty(e){return this.min(1,e)}};Dr.create=(t,e)=>new Dr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...Q(e)});St=class t extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){let u=this._getOrReturnCtx(e);return N(u,{code:O.invalid_type,expected:M.object,received:u.parsedType}),W}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof or&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=o[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Zt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof or){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")a.length>0&&(N(s,{code:O.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Zt(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>Je.mergeObjectSync(n,u)):Je.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return F.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:F.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:I.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ie.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ie.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Ns(this)}partial(e){let r={};for(let n of ie.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ie.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof bt;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return Hx(ie.objectKeys(this.shape))}};St.create=(t,e)=>new St({shape:()=>t,unknownKeys:"strip",catchall:or.create(),typeName:I.ZodObject,...Q(e)});St.strictCreate=(t,e)=>new St({shape:()=>t,unknownKeys:"strict",catchall:or.create(),typeName:I.ZodObject,...Q(e)});St.lazycreate=(t,e)=>new St({shape:t,unknownKeys:"strip",catchall:or.create(),typeName:I.ZodObject,...Q(e)});Un=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new vt(a.ctx.common.issues));return N(r,{code:O.invalid_union,unionErrors:i}),W}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new vt(c));return N(r,{code:O.invalid_union,unionErrors:a}),W}}get options(){return this._def.options}};Un.create=(t,e)=>new Un({options:t,typeName:I.ZodUnion,...Q(e)});Ar=t=>t instanceof Zn?Ar(t.schema):t instanceof Bt?Ar(t.innerType()):t instanceof Bn?[t.value]:t instanceof qn?t.options:t instanceof Vn?ie.objectValues(t.enum):t instanceof Wn?Ar(t._def.innerType):t instanceof Ln?[void 0]:t instanceof Fn?[null]:t instanceof bt?[void 0,...Ar(t.unwrap())]:t instanceof Sr?[null,...Ar(t.unwrap())]:t instanceof Uo||t instanceof Kn?Ar(t.unwrap()):t instanceof Gn?Ar(t._def.innerType):[],Ha=class t extends te{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return N(r,{code:O.invalid_type,expected:M.object,received:r.parsedType}),W;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(N(r,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Ar(o.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(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:I.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Q(n)})}};Hn=class extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Fa(o)||Fa(i))return W;let a=Md(o.value,i.value);return a.valid?((Ua(o)||Ua(i))&&r.dirty(),{status:r.value,value:a.data}):(N(n,{code:O.invalid_intersection_types}),W)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Hn.create=(t,e,r)=>new Hn({left:t,right:e,typeName:I.ZodIntersection,...Q(r)});br=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return N(n,{code:O.invalid_type,expected:M.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return N(n,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&n.data.length>this._def.items.length&&(N(n,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Zt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Je.mergeArray(r,i)):Je.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};br.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new br({items:t,typeName:I.ZodTuple,rest:null,...Q(e)})};Za=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return N(n,{code:O.invalid_type,expected:M.object,received:n.parsedType}),W;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Zt(n,a,n.path,a)),value:i._parse(new Zt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Je.mergeObjectAsync(r,s):Je.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof te?new t({keyType:e,valueType:r,typeName:I.ZodRecord,...Q(n)}):new t({keyType:rn.create(),valueType:e,typeName:I.ZodRecord,...Q(r)})}},js=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return N(n,{code:O.invalid_type,expected:M.map,received:n.parsedType}),W;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Zt(n,a,n.path,[u,"key"])),value:o._parse(new Zt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};js.create=(t,e,r)=>new js({valueType:e,keyType:t,typeName:I.ZodMap,...Q(r)});zs=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return N(n,{code:O.invalid_type,expected:M.set,received:n.parsedType}),W;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(N(n,{code:O.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(N(n,{code:O.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return W;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Zt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:F.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:F.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};zs.create=(t,e)=>new zs({valueType:t,minSize:null,maxSize:null,typeName:I.ZodSet,...Q(e)});Ba=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return N(r,{code:O.invalid_type,expected:M.function,received:r.parsedType}),W;function n(a,c){return Fo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Is(),Ir].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:c}})}function s(a,c){return Fo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Is(),Ir].filter(u=>!!u),issueData:{code:O.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof sn){let a=this;return st(async function(...c){let u=new vt([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(s(l,f)),u})})}else{let a=this;return st(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new vt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new vt([s(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:br.create(e).rest(Nr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||br.create([]).rest(Nr.create()),returns:r||Nr.create(),typeName:I.ZodFunction,...Q(n)})}},Zn=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Zn.create=(t,e)=>new Zn({getter:t,typeName:I.ZodLazy,...Q(e)});Bn=class extends te{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return N(r,{received:r.data,code:O.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Bn.create=(t,e)=>new Bn({value:t,typeName:I.ZodLiteral,...Q(e)});qn=class t extends te{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ie.joinValues(n),received:r.parsedType,code:O.invalid_type}),W}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{received:r.data,code:O.invalid_enum_value,options:n}),W}return st(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};qn.create=Hx;Vn=class extends te{_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let s=ie.objectValues(r);return N(n,{expected:ie.joinValues(s),received:n.parsedType,code:O.invalid_type}),W}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ie.objectValues(r);return N(n,{received:n.data,code:O.invalid_enum_value,options:s}),W}return st(e.data)}get enum(){return this._def.values}};Vn.create=(t,e)=>new Vn({values:t,typeName:I.ZodNativeEnum,...Q(e)});sn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return N(r,{code:O.invalid_type,expected:M.promise,received:r.parsedType}),W;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return st(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};sn.create=(t,e)=>new sn({type:t,typeName:I.ZodPromise,...Q(e)});Bt=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{N(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return W;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?W:c.status==="dirty"?Nn(c.value):r.value==="dirty"?Nn(c.value):c});{if(r.value==="aborted")return W;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?W:a.status==="dirty"?Nn(a.value):r.value==="dirty"?Nn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?W:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?W:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!tn(i))return W;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>tn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):W);ie.assertNever(s)}};Bt.create=(t,e,r)=>new Bt({schema:t,typeName:I.ZodEffects,effect:e,...Q(r)});Bt.createWithPreprocess=(t,e,r)=>new Bt({schema:e,effect:{type:"preprocess",transform:t},typeName:I.ZodEffects,...Q(r)});bt=class extends te{_parse(e){return this._getType(e)===M.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bt.create=(t,e)=>new bt({innerType:t,typeName:I.ZodOptional,...Q(e)});Sr=class extends te{_parse(e){return this._getType(e)===M.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Sr.create=(t,e)=>new Sr({innerType:t,typeName:I.ZodNullable,...Q(e)});Wn=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Wn.create=(t,e)=>new Wn({innerType:t,typeName:I.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});Gn=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return As(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Gn.create=(t,e)=>new Gn({innerType:t,typeName:I.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Ls=class extends te{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.nan,received:n.parsedType}),W}return{status:"valid",value:e.data}}};Ls.create=t=>new Ls({typeName:I.ZodNaN,...Q(t)});cC=Symbol("zod_brand"),Uo=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ho=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?W:o.status==="dirty"?(r.dirty(),Nn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?W:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:I.ZodPipeline})}},Kn=class extends te{_parse(e){let r=this._def.innerType._parse(e),n=s=>(tn(s)&&(s.value=Object.freeze(s.value)),s);return As(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Kn.create=(t,e)=>new Kn({innerType:t,typeName:I.ZodReadonly,...Q(e)});uC={object:St.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(I||(I={}));lC=(t,e={message:`Input not instance of ${t.name}`})=>Zx(r=>r instanceof t,e),Bx=rn.create,qx=Dn.create,dC=Ls.create,pC=Mn.create,Vx=jn.create,mC=zn.create,fC=Ds.create,hC=Ln.create,gC=Fn.create,yC=nn.create,_C=Nr.create,xC=or.create,vC=Ms.create,bC=Dr.create,jd=St.create,SC=St.strictCreate,kC=Un.create,wC=Ha.create,EC=Hn.create,$C=br.create,TC=Za.create,PC=js.create,RC=zs.create,CC=Ba.create,OC=Zn.create,IC=Bn.create,AC=qn.create,NC=Vn.create,DC=sn.create,MC=Bt.create,jC=bt.create,zC=Sr.create,LC=Bt.createWithPreprocess,FC=Ho.create,UC=()=>Bx().optional(),HC=()=>qx().optional(),ZC=()=>Vx().optional(),BC={string:(t=>rn.create({...t,coerce:!0})),number:(t=>Dn.create({...t,coerce:!0})),boolean:(t=>jn.create({...t,coerce:!0})),bigint:(t=>Mn.create({...t,coerce:!0})),date:(t=>zn.create({...t,coerce:!0}))},qC=W});var U={};Le(U,{BRAND:()=>cC,DIRTY:()=>Nn,EMPTY_PATH:()=>FR,INVALID:()=>W,NEVER:()=>qC,OK:()=>st,ParseStatus:()=>Je,Schema:()=>te,ZodAny:()=>nn,ZodArray:()=>Dr,ZodBigInt:()=>Mn,ZodBoolean:()=>jn,ZodBranded:()=>Uo,ZodCatch:()=>Gn,ZodDate:()=>zn,ZodDefault:()=>Wn,ZodDiscriminatedUnion:()=>Ha,ZodEffects:()=>Bt,ZodEnum:()=>qn,ZodError:()=>vt,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>Ba,ZodIntersection:()=>Hn,ZodIssueCode:()=>O,ZodLazy:()=>Zn,ZodLiteral:()=>Bn,ZodMap:()=>js,ZodNaN:()=>Ls,ZodNativeEnum:()=>Vn,ZodNever:()=>or,ZodNull:()=>Fn,ZodNullable:()=>Sr,ZodNumber:()=>Dn,ZodObject:()=>St,ZodOptional:()=>bt,ZodParsedType:()=>M,ZodPipeline:()=>Ho,ZodPromise:()=>sn,ZodReadonly:()=>Kn,ZodRecord:()=>Za,ZodSchema:()=>te,ZodSet:()=>zs,ZodString:()=>rn,ZodSymbol:()=>Ds,ZodTransformer:()=>Bt,ZodTuple:()=>br,ZodType:()=>te,ZodUndefined:()=>Ln,ZodUnion:()=>Un,ZodUnknown:()=>Nr,ZodVoid:()=>Ms,addIssueToContext:()=>N,any:()=>yC,array:()=>bC,bigint:()=>pC,boolean:()=>Vx,coerce:()=>BC,custom:()=>Zx,date:()=>mC,datetimeRegex:()=>Ux,defaultErrorMap:()=>Ir,discriminatedUnion:()=>wC,effect:()=>MC,enum:()=>AC,function:()=>CC,getErrorMap:()=>Is,getParsedType:()=>vr,instanceof:()=>lC,intersection:()=>EC,isAborted:()=>Fa,isAsync:()=>As,isDirty:()=>Ua,isValid:()=>tn,late:()=>uC,lazy:()=>OC,literal:()=>IC,makeIssue:()=>Fo,map:()=>PC,nan:()=>dC,nativeEnum:()=>NC,never:()=>xC,null:()=>gC,nullable:()=>zC,number:()=>qx,object:()=>jd,objectUtil:()=>Id,oboolean:()=>ZC,onumber:()=>HC,optional:()=>jC,ostring:()=>UC,pipeline:()=>FC,preprocess:()=>LC,promise:()=>DC,quotelessJson:()=>jR,record:()=>TC,set:()=>RC,setErrorMap:()=>LR,strictObject:()=>SC,string:()=>Bx,symbol:()=>fC,transformer:()=>MC,tuple:()=>$C,undefined:()=>hC,union:()=>kC,unknown:()=>_C,util:()=>ie,void:()=>vC});var qa=b(()=>{La();Nd();Dx();Lo();Wx();za()});var Zo=b(()=>{qa()});function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let u=r?.Parent?new o:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function It(t){return t&&Object.assign(Va,t),Va}var WC,Mr,Va,Fs=b(()=>{WC=Object.freeze({status:"aborted"});Mr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Va={}});var ce={};Le(ce,{BIGINT_FORMAT_RANGES:()=>Kx,Class:()=>Ld,NUMBER_FORMAT_RANGES:()=>Vd,aborted:()=>Yn,allowsEval:()=>Zd,assert:()=>XC,assertEqual:()=>GC,assertIs:()=>JC,assertNever:()=>YC,assertNotEqual:()=>KC,assignProp:()=>Hd,cached:()=>Vo,captureStackTrace:()=>Ga,cleanEnum:()=>dO,cleanRegex:()=>Go,clone:()=>At,createTransparentProxy:()=>sO,defineLazy:()=>ke,esc:()=>Jn,escapeRegex:()=>on,extend:()=>aO,finalizeIssue:()=>ir,floatSafeRemainder:()=>Ud,getElementAtPath:()=>QC,getEnumValues:()=>qo,getLengthableOrigin:()=>Ko,getParsedType:()=>nO,getSizableOrigin:()=>Jx,isObject:()=>Us,isPlainObject:()=>Hs,issue:()=>Wd,joinValues:()=>Wa,jsonStringifyReplacer:()=>Fd,merge:()=>cO,normalizeParams:()=>G,nullish:()=>Wo,numKeys:()=>rO,omit:()=>iO,optionalKeys:()=>qd,partial:()=>uO,pick:()=>oO,prefixIssues:()=>kr,primitiveTypes:()=>Gx,promiseAllObject:()=>eO,propertyKeyTypes:()=>Bd,randomString:()=>tO,required:()=>lO,stringifyPrimitive:()=>Ka,unwrapMessage:()=>Bo});function GC(t){return t}function KC(t){return t}function JC(t){}function YC(t){throw new Error}function XC(t){}function qo(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function Wa(t,e="|"){return t.map(r=>Ka(r)).join(e)}function Fd(t,e){return typeof e=="bigint"?e.toString():e}function Vo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Wo(t){return t==null}function Go(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ud(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ke(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function Hd(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function QC(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function eO(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=n[o];return s})}function tO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Jn(t){return JSON.stringify(t)}function Us(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hs(t){if(Us(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Us(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function rO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function on(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function At(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function G(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function sO(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,o){return e??(e=t()),Reflect.set(e,n,s,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function Ka(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function qd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function oO(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return At(t,{...t._zod.def,shape:r,checks:[]})}function iO(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return At(t,{...t._zod.def,shape:r,checks:[]})}function aO(t,e){if(!Hs(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Hd(this,"shape",n),n},checks:[]};return At(t,r)}function cO(t,e){return At(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Hd(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function uO(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return At(e,{...e._zod.def,shape:s,checks:[]})}function lO(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(let o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return At(e,{...e._zod.def,shape:s,checks:[]})}function Yn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function kr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Bo(t){return typeof t=="string"?t:t?.message}function ir(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=Bo(t.inst?._zod.def?.error?.(t))??Bo(e?.error?.(t))??Bo(r.customError?.(t))??Bo(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Jx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ko(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Wd(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function dO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ga,Zd,nO,Bd,Gx,Vd,Kx,Ld,wr=b(()=>{Ga=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Zd=Vo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});nO=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}`)}},Bd=new Set(["string","number","symbol"]),Gx=new Set(["string","number","bigint","boolean","symbol","undefined"]);Vd={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]},Kx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Ld=class{constructor(...e){}}});function Gd(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function Kd(t,e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>s({issues:a}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(t),n}var Yx,Ja,Jo,Jd=b(()=>{Fs();wr();Yx=(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,Fd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ja=w("$ZodError",Yx),Jo=w("$ZodError",Yx,{Parent:Error})});var Yd,Xd,Qd,ep,tp,Xn,rp,Qn,np=b(()=>{Fs();Jd();wr();Yd=t=>(e,r,n,s)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Mr;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>ir(c,o,It())));throw Ga(a,s?.callee),a}return i.value},Xd=Yd(Jo),Qd=t=>async(e,r,n,s)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>ir(c,o,It())));throw Ga(a,s?.callee),a}return i.value},ep=Qd(Jo),tp=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Mr;return o.issues.length?{success:!1,error:new(t??Ja)(o.issues.map(i=>ir(i,s,It())))}:{success:!0,data:o.value}},Xn=tp(Jo),rp=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>ir(i,s,It())))}:{success:!0,data:o.value}},Qn=rp(Jo)});function av(){return new RegExp(mO,"u")}function yv(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 _v(t){return new RegExp(`^${yv(t)}$`)}function xv(t){let e=yv({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${hv}T(?:${n})$`)}var Xx,Qx,ev,tv,rv,nv,sv,ov,sp,iv,mO,cv,uv,lv,dv,pv,op,mv,fv,hv,gv,vv,bv,Sv,kv,wv,Ev,$v,Xa=b(()=>{Xx=/^[cC][^\s-]{8,}$/,Qx=/^[0-9a-z]+$/,ev=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tv=/^[0-9a-vA-V]{20}$/,rv=/^[A-Za-z0-9]{27}$/,nv=/^[a-zA-Z0-9_-]{21}$/,sv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ov=/^([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})$/,sp=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)$/,iv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,mO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";cv=/^(?:(?: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])$/,uv=/^(([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})$/,lv=/^((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])$/,dv=/^(([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])$/,pv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,op=/^[A-Za-z0-9_-]*$/,mv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,fv=/^\+(?:[0-9]){6,14}[0-9]$/,hv="(?:(?:\\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])))",gv=new RegExp(`^${hv}$`);vv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},bv=/^\d+$/,Sv=/^-?\d+(?:\.\d+)?/i,kv=/true|false/i,wv=/null/i,Ev=/^[^A-Z]*$/,$v=/^[^a-z]*$/});var Ye,Tv,ip,ap,Pv,Rv,Cv,Ov,Iv,Yo,Av,Nv,Dv,Mv,jv,zv,Lv,Qa=b(()=>{Fs();Xa();wr();Ye=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Tv={number:"number",bigint:"bigint",object:"date"},ip=w("$ZodCheckLessThan",(t,e)=>{Ye.init(t,e);let r=Tv[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ap=w("$ZodCheckGreaterThan",(t,e)=>{Ye.init(t,e);let r=Tv[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Pv=w("$ZodCheckMultipleOf",(t,e)=>{Ye.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Ud(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Rv=w("$ZodCheckNumberFormat",(t,e)=>{Ye.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Vd[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,r&&(a.pattern=bv)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}}),Cv=w("$ZodCheckMaxLength",(t,e)=>{var r;Ye.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Wo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let i=Ko(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Ov=w("$ZodCheckMinLength",(t,e)=>{var r;Ye.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Wo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let i=Ko(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Iv=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ye.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Wo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,o=s.length;if(o===e.length)return;let i=Ko(s),a=o>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Yo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ye.init(t,e),t._zod.onattach.push(s=>{let o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Av=w("$ZodCheckRegex",(t,e)=>{Yo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Nv=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ev),Yo.init(t,e)}),Dv=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=$v),Yo.init(t,e)}),Mv=w("$ZodCheckIncludes",(t,e)=>{Ye.init(t,e);let r=on(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),jv=w("$ZodCheckStartsWith",(t,e)=>{Ye.init(t,e);let r=new RegExp(`^${on(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),zv=w("$ZodCheckEndsWith",(t,e)=>{Ye.init(t,e);let r=new RegExp(`.*${on(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Lv=w("$ZodCheckOverwrite",(t,e)=>{Ye.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ec,cp=b(()=>{ec=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
34
34
  `).filter(i=>i),s=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
35
- `))}}});var Fv,ap=b(()=>{Fv={major:4,minor:0,patch:0}});function eb(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function lO(t){if(!np.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return eb(r)}function dO(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}function Uv(t,e,r){t.issues.length&&e.issues.push(...kr(r,t.issues)),e.value[r]=t.value}function ec(t,e,r){t.issues.length&&e.issues.push(...kr(r,t.issues)),e.value[r]=t.value}function Hv(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...kr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Zv(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>ir(o,n,It())))}),e}function cp(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(Hs(t)&&Hs(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(let o of n){let i=cp(t[o],e[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};s[o]=i.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let s=t[n],o=e[n],i=cp(s,o);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Bv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Jn(t))return t;let n=cp(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function qv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Vv(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Wv(t,e,r){return Jn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Gv(t){return t.value=Object.freeze(t.value),t}function Kv(t,e,r,n){if(!t){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(qd(s))}}var xe,Yo,we,up,lp,dp,pp,mp,fp,hp,gp,yp,_p,xp,Jv,Yv,Xv,Qv,vp,bp,Sp,kp,wp,Ep,$p,Tp,tc,Pp,Rp,Cp,Op,Ip,Ap,rc,nc,Np,Dp,Mp,jp,zp,Lp,Fp,Up,Hp,Zp,Bp,qp,Vp,Wp,Gp,tb=b(()=>{Xa();Fs();ip();tp();Ya();wr();ap();wr();xe=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Fv;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let s of n)for(let o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let s=(o,i,a)=>{let c=Jn(o),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(c)continue;let l=o.issues.length,p=d._zod.check(o);if(p instanceof Promise&&a?.async===!1)throw new Mr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,o.issues.length!==l&&(c||(c=Jn(o,l)))});else{if(o.issues.length===l)continue;c||(c=Jn(o,l))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{let a=t._zod.parse(o,i);if(a instanceof Promise){if(i.async===!1)throw new Mr;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=Yn(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Xn(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Yo=w("$ZodString",(t,e)=>{xe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??xv(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),we=w("$ZodStringFormat",(t,e)=>{Jo.init(t,e),Yo.init(t,e)}),up=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=sv),we.init(t,e)}),lp=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=rp(n))}else e.pattern??(e.pattern=rp());we.init(t,e)}),dp=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ov),we.init(t,e)}),pp=w("$ZodURL",(t,e)=>{we.init(t,e),t._zod.check=r=>{try{let n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:pv.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),mp=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=iv()),we.init(t,e)}),fp=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=rv),we.init(t,e)}),hp=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Yx),we.init(t,e)}),gp=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Xx),we.init(t,e)}),yp=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Qx),we.init(t,e)}),_p=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ev),we.init(t,e)}),xp=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=tv),we.init(t,e)}),Jv=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=_v(e)),we.init(t,e)}),Yv=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=hv),we.init(t,e)}),Xv=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=yv(e)),we.init(t,e)}),Qv=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=nv),we.init(t,e)}),vp=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=av),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),bp=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=cv),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Sp=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=uv),we.init(t,e)}),kp=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=lv),we.init(t,e),t._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});wp=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=dv),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{eb(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Ep=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=np),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{lO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),$p=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=mv),we.init(t,e)});Tp=w("$ZodJWT",(t,e)=>{we.init(t,e),t._zod.check=r=>{dO(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),tc=w("$ZodNumber",(t,e)=>{xe.init(t,e),t._zod.pattern=t._zod.bag.pattern??bv,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;let o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),Pp=w("$ZodNumber",(t,e)=>{Pv.init(t,e),tc.init(t,e)}),Rp=w("$ZodBoolean",(t,e)=>{xe.init(t,e),t._zod.pattern=Sv,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),Cp=w("$ZodNull",(t,e)=>{xe.init(t,e),t._zod.pattern=kv,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),Op=w("$ZodUnknown",(t,e)=>{xe.init(t,e),t._zod.parse=r=>r}),Ip=w("$ZodNever",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Ap=w("$ZodArray",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);let o=[];for(let i=0;i<s.length;i++){let a=s[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(u=>Uv(u,r,i))):Uv(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});rc=w("$ZodObject",(t,e)=>{xe.init(t,e);let r=qo(()=>{let l=Object.keys(e.shape);for(let f of l)if(!(e.shape[f]instanceof xe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Zd(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(p)}});ke(t._zod,"propValues",()=>{let l=e.shape,p={};for(let f in l){let m=l[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let h of m.values)p[f].add(h)}}return p});let n=l=>{let p=new Qa(["shape","payload","ctx"]),f=r.value,m=v=>{let y=Kn(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of f.keys)h[v]=`key_${g++}`;p.write("const newResult = {}");for(let v of f.keys)if(f.optionalKeys.has(v)){let y=h[v];p.write(`const ${y} = ${m(v)};`);let x=Kn(v);p.write(`
35
+ `))}}});var Uv,up=b(()=>{Uv={major:4,minor:0,patch:0}});function tb(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function fO(t){if(!op.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return tb(r)}function hO(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}function Hv(t,e,r){t.issues.length&&e.issues.push(...kr(r,t.issues)),e.value[r]=t.value}function tc(t,e,r){t.issues.length&&e.issues.push(...kr(r,t.issues)),e.value[r]=t.value}function Zv(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...kr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Bv(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>ir(o,n,It())))}),e}function lp(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(Hs(t)&&Hs(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(let o of n){let i=lp(t[o],e[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};s[o]=i.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let s=t[n],o=e[n],i=lp(s,o);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function qv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Yn(t))return t;let n=lp(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Vv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Wv(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Gv(t,e,r){return Yn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Kv(t){return t.value=Object.freeze(t.value),t}function Jv(t,e,r,n){if(!t){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Wd(s))}}var xe,Xo,we,dp,pp,mp,fp,hp,gp,yp,_p,xp,vp,bp,Yv,Xv,Qv,eb,Sp,kp,wp,Ep,$p,Tp,Pp,Rp,rc,Cp,Op,Ip,Ap,Np,Dp,nc,sc,Mp,jp,zp,Lp,Fp,Up,Hp,Zp,Bp,qp,Vp,Wp,Gp,Kp,Jp,rb=b(()=>{Qa();Fs();cp();np();Xa();wr();up();wr();xe=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Uv;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let s of n)for(let o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let s=(o,i,a)=>{let c=Yn(o),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(c)continue;let l=o.issues.length,p=d._zod.check(o);if(p instanceof Promise&&a?.async===!1)throw new Mr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,o.issues.length!==l&&(c||(c=Yn(o,l)))});else{if(o.issues.length===l)continue;c||(c=Yn(o,l))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{let a=t._zod.parse(o,i);if(a instanceof Promise){if(i.async===!1)throw new Mr;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=Xn(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Qn(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Xo=w("$ZodString",(t,e)=>{xe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??vv(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),we=w("$ZodStringFormat",(t,e)=>{Yo.init(t,e),Xo.init(t,e)}),dp=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ov),we.init(t,e)}),pp=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=sp(n))}else e.pattern??(e.pattern=sp());we.init(t,e)}),mp=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=iv),we.init(t,e)}),fp=w("$ZodURL",(t,e)=>{we.init(t,e),t._zod.check=r=>{try{let n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:mv.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),hp=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=av()),we.init(t,e)}),gp=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=nv),we.init(t,e)}),yp=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Xx),we.init(t,e)}),_p=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Qx),we.init(t,e)}),xp=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ev),we.init(t,e)}),vp=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=tv),we.init(t,e)}),bp=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=rv),we.init(t,e)}),Yv=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=xv(e)),we.init(t,e)}),Xv=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=gv),we.init(t,e)}),Qv=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=_v(e)),we.init(t,e)}),eb=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=sv),we.init(t,e)}),Sp=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=cv),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),kp=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=uv),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),wp=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=lv),we.init(t,e)}),Ep=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=dv),we.init(t,e),t._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});$p=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=pv),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{tb(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Tp=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=op),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{fO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Pp=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=fv),we.init(t,e)});Rp=w("$ZodJWT",(t,e)=>{we.init(t,e),t._zod.check=r=>{hO(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),rc=w("$ZodNumber",(t,e)=>{xe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Sv,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;let o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),Cp=w("$ZodNumber",(t,e)=>{Rv.init(t,e),rc.init(t,e)}),Op=w("$ZodBoolean",(t,e)=>{xe.init(t,e),t._zod.pattern=kv,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),Ip=w("$ZodNull",(t,e)=>{xe.init(t,e),t._zod.pattern=wv,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),Ap=w("$ZodUnknown",(t,e)=>{xe.init(t,e),t._zod.parse=r=>r}),Np=w("$ZodNever",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Dp=w("$ZodArray",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);let o=[];for(let i=0;i<s.length;i++){let a=s[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(u=>Hv(u,r,i))):Hv(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});nc=w("$ZodObject",(t,e)=>{xe.init(t,e);let r=Vo(()=>{let l=Object.keys(e.shape);for(let f of l)if(!(e.shape[f]instanceof xe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=qd(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(p)}});ke(t._zod,"propValues",()=>{let l=e.shape,p={};for(let f in l){let m=l[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let h of m.values)p[f].add(h)}}return p});let n=l=>{let p=new ec(["shape","payload","ctx"]),f=r.value,m=v=>{let y=Jn(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of f.keys)h[v]=`key_${g++}`;p.write("const newResult = {}");for(let v of f.keys)if(f.optionalKeys.has(v)){let y=h[v];p.write(`const ${y} = ${m(v)};`);let x=Jn(v);p.write(`
36
36
  if (${y}.issues.length) {
37
37
  if (input[${x}] === undefined) {
38
38
  if (${x} in input) {
@@ -54,24 +54,24 @@ Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ct
54
54
  `)}else{let y=h[v];p.write(`const ${y} = ${m(v)};`),p.write(`
55
55
  if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
56
56
  ...iss,
57
- path: iss.path ? [${Kn(v)}, ...iss.path] : [${Kn(v)}]
58
- })));`),p.write(`newResult[${Kn(v)}] = ${y}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(v,y)=>_(l,v,y)},s,o=Us,i=!qa.jitless,c=i&&Ud.value,u=e.catchall,d;t._zod.parse=(l,p)=>{d??(d=r.value);let f=l.value;if(!o(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)s||(s=n(e.shape)),l=s(l,p);else{l.value={};let y=d.shape;for(let x of d.keys){let k=y[x],R=k._zod.run({value:f[x],issues:[]},p),$=k._zod.optin==="optional"&&k._zod.optout==="optional";R instanceof Promise?m.push(R.then(P=>$?Hv(P,l,x,f):ec(P,l,x))):$?Hv(R,l,x,f):ec(R,l,x)}}if(!u)return m.length?Promise.all(m).then(()=>l):l;let h=[],g=d.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(f)){if(g.has(y))continue;if(v==="never"){h.push(y);continue}let x=_.run({value:f[y],issues:[]},p);x instanceof Promise?m.push(x.then(k=>ec(k,l,y))):ec(x,l,y)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>l):l}});nc=w("$ZodUnion",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ke(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Wo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),s=!0;else{if(a.issues.length===0)return a;o.push(a)}}return s?Promise.all(o).then(i=>Zv(i,r,t,n)):Zv(o,r,t,n)}}),Np=w("$ZodDiscriminatedUnion",(t,e)=>{nc.init(t,e);let r=t._zod.parse;ke(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=qo(()=>{let s=e.options,o=new Map;for(let i of s){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(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});t._zod.parse=(s,o)=>{let i=s.value;if(!Us(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),Dp=w("$ZodIntersection",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,o=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>Bv(r,c,u)):Bv(r,o,i)}});Mp=w("$ZodRecord",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Hs(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let o=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:s[c],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...kr(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...kr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(s)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>ir(u,n,It())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...kr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...kr(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),jp=w("$ZodEnum",(t,e)=>{xe.init(t,e);let r=Bo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Hd.has(typeof n)).map(n=>typeof n=="string"?on(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),zp=w("$ZodLiteral",(t,e)=>{xe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?on(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),Lp=w("$ZodTransform",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Mr;return r.value=s,r}}),Fp=w("$ZodOptional",(t,e)=>{xe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Wo(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Up=w("$ZodNullable",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Wo(r.source)}|null)$`):void 0}),ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Hp=w("$ZodDefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>qv(o,e)):qv(s,e)}});Zp=w("$ZodPrefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Bp=w("$ZodNonOptional",(t,e)=>{xe.init(t,e),ke(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Vv(o,t)):Vv(s,t)}});qp=w("$ZodCatch",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>ir(i,n,It()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>ir(o,n,It()))},input:r.value}),r.issues=[]),r)}}),Vp=w("$ZodPipe",(t,e)=>{xe.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Wv(o,e,n)):Wv(s,e,n)}});Wp=w("$ZodReadonly",(t,e)=>{xe.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Gv):Gv(s)}});Gp=w("$ZodCustom",(t,e)=>{Ye.init(t,e),xe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Kv(o,r,n,t));Kv(s,r,n,t)}})});function rb(){return{localeError:mO()}}var pO,mO,nb=b(()=>{wr();pO=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},mO=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${pO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ga(n.values[0])}`:`Invalid option: expected one of ${Va(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Va(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var sc=b(()=>{});function sb(){return new Xo}var Xo,an,Jp=b(()=>{Xo=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};an=sb()});function Yp(t,e){return new t({type:"string",...G(e)})}function Xp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...G(e)})}function oc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...G(e)})}function Qp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...G(e)})}function em(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(e)})}function tm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(e)})}function rm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(e)})}function nm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...G(e)})}function sm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...G(e)})}function om(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(e)})}function im(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...G(e)})}function am(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(e)})}function cm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...G(e)})}function um(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...G(e)})}function lm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(e)})}function dm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(e)})}function pm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(e)})}function mm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(e)})}function fm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(e)})}function hm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...G(e)})}function gm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...G(e)})}function ym(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...G(e)})}function _m(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...G(e)})}function ob(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(e)})}function ib(t,e){return new t({type:"string",format:"date",check:"string_format",...G(e)})}function ab(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...G(e)})}function cb(t,e){return new t({type:"string",format:"duration",check:"string_format",...G(e)})}function xm(t,e){return new t({type:"number",checks:[],...G(e)})}function vm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...G(e)})}function bm(t,e){return new t({type:"boolean",...G(e)})}function Sm(t,e){return new t({type:"null",...G(e)})}function km(t){return new t({type:"unknown"})}function wm(t,e){return new t({type:"never",...G(e)})}function ic(t,e){return new sp({check:"less_than",...G(e),value:t,inclusive:!1})}function Qo(t,e){return new sp({check:"less_than",...G(e),value:t,inclusive:!0})}function ac(t,e){return new op({check:"greater_than",...G(e),value:t,inclusive:!1})}function ei(t,e){return new op({check:"greater_than",...G(e),value:t,inclusive:!0})}function cc(t,e){return new Tv({check:"multiple_of",...G(e),value:t})}function uc(t,e){return new Rv({check:"max_length",...G(e),maximum:t})}function Zs(t,e){return new Cv({check:"min_length",...G(e),minimum:t})}function lc(t,e){return new Ov({check:"length_equals",...G(e),length:t})}function Em(t,e){return new Iv({check:"string_format",format:"regex",...G(e),pattern:t})}function $m(t){return new Av({check:"string_format",format:"lowercase",...G(t)})}function Tm(t){return new Nv({check:"string_format",format:"uppercase",...G(t)})}function Pm(t,e){return new Dv({check:"string_format",format:"includes",...G(e),includes:t})}function Rm(t,e){return new Mv({check:"string_format",format:"starts_with",...G(e),prefix:t})}function Cm(t,e){return new jv({check:"string_format",format:"ends_with",...G(e),suffix:t})}function Qn(t){return new zv({check:"overwrite",tx:t})}function Om(t){return Qn(e=>e.normalize(t))}function Im(){return Qn(t=>t.trim())}function Am(){return Qn(t=>t.toLowerCase())}function Nm(){return Qn(t=>t.toUpperCase())}function ub(t,e,r){return new t({type:"array",element:e,...G(r)})}function Dm(t,e,r){let n=G(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Mm(t,e,r){return new t({type:"custom",check:"custom",fn:e,...G(r)})}var lb=b(()=>{Xa();wr()});var db=b(()=>{});function jm(t,e){if(t instanceof Xo){let n=new dc(e),s={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,u]=a;o[c]=n.emit(u,{...e,external:i})}if(Object.keys(s).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let r=new dc(e);return r.process(t),r.emit(t,e)}function Ve(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let s=t._zod.def;switch(s.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 Ve(s.element,r);case"object":{for(let o in s.shape)if(Ve(s.shape[o],r))return!0;return!1}case"union":{for(let o of s.options)if(Ve(o,r))return!0;return!1}case"intersection":return Ve(s.left,r)||Ve(s.right,r);case"tuple":{for(let o of s.items)if(Ve(o,r))return!0;return!!(s.rest&&Ve(s.rest,r))}case"record":return Ve(s.keyType,r)||Ve(s.valueType,r);case"map":return Ve(s.keyType,r)||Ve(s.valueType,r);case"set":return Ve(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ve(s.innerType,r);case"lazy":return Ve(s.getter(),r);case"default":return Ve(s.innerType,r);case"prefault":return Ve(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ve(s.in,r)||Ve(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var dc,pb=b(()=>{Jp();wr();dc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??an,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,l),this.seen.get(p).isParent=!0;else{let f=a.schema;switch(s.type){case"string":{let m=f;m.type="string";let{minimum:h,maximum:g,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),_&&(m.format=o[_]??_,m.format===""&&delete m.format),y&&(m.contentEncoding=y),v&&v.size>0){let x=[...v];x.length===1?m.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{let m=f,{minimum:h,maximum:g,format:_,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?m.type="integer":m.type="number",typeof x=="number"&&(m.exclusiveMinimum=x),typeof h=="number"&&(m.minimum=h,typeof x=="number"&&(x>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof y=="number"&&(m.exclusiveMaximum=y),typeof g=="number"&&(m.maximum=g,typeof y=="number"&&(y<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof v=="number"&&(m.multipleOf=v);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(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let h=s.shape;for(let v in h)m.properties[v]=this.process(h[v],{...l,path:[...l.path,"properties",v]});let g=new Set(Object.keys(h)),_=new Set([...g].filter(v=>{let y=s.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));_.size>0&&(m.required=Array.from(_)),s.catchall?._zod.def.type==="never"?m.additionalProperties=!1:s.catchall?s.catchall&&(m.additionalProperties=this.process(s.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=s.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let m=f,h=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(h)?h.allOf:[h],..._(g)?g.allOf:[g]];m.allOf=v;break}case"tuple":{let m=f;m.type="array";let h=s.items.map((v,y)=>this.process(v,{...l,path:[...l.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,s.rest){let v=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?m.items=v:m.additionalItems=v}s.rest&&(m.items=this.process(s.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof _=="number"&&(m.maxItems=_);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(s.keyType,{...l,path:[...l.path,"propertyNames"]}),m.additionalProperties=this.process(s.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=f,h=Bo(s.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 s.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:_,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),_!==void 0&&(h.maxLength=_),v?v.length===1?(h.contentMediaType=v[0],Object.assign(m,h)):m.anyOf=v.map(y=>({...h,contentMediaType:y})):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(s.innerType,l);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let m;try{m=s.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"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(m,l),a.ref=m;break}case"readonly":{this.process(s.innerType,l),a.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,l),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,l),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"&&Ve(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let _=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=_,{defId:_,ref:`${g("__shared")}#/${l}/${_}`}}if(d[1]===s)return{ref:"#"};let f=`#/${l}/`,m=d[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:p,defId:f}=o(d);l.def={...l.schema},f&&(l.defId=f);let m=l.schema;for(let h in m)delete m[h];m.$ref=p};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
57
+ path: iss.path ? [${Jn(v)}, ...iss.path] : [${Jn(v)}]
58
+ })));`),p.write(`newResult[${Jn(v)}] = ${y}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(v,y)=>_(l,v,y)},s,o=Us,i=!Va.jitless,c=i&&Zd.value,u=e.catchall,d;t._zod.parse=(l,p)=>{d??(d=r.value);let f=l.value;if(!o(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)s||(s=n(e.shape)),l=s(l,p);else{l.value={};let y=d.shape;for(let x of d.keys){let k=y[x],R=k._zod.run({value:f[x],issues:[]},p),$=k._zod.optin==="optional"&&k._zod.optout==="optional";R instanceof Promise?m.push(R.then(P=>$?Zv(P,l,x,f):tc(P,l,x))):$?Zv(R,l,x,f):tc(R,l,x)}}if(!u)return m.length?Promise.all(m).then(()=>l):l;let h=[],g=d.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(f)){if(g.has(y))continue;if(v==="never"){h.push(y);continue}let x=_.run({value:f[y],issues:[]},p);x instanceof Promise?m.push(x.then(k=>tc(k,l,y))):tc(x,l,y)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>l):l}});sc=w("$ZodUnion",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ke(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Go(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),s=!0;else{if(a.issues.length===0)return a;o.push(a)}}return s?Promise.all(o).then(i=>Bv(i,r,t,n)):Bv(o,r,t,n)}}),Mp=w("$ZodDiscriminatedUnion",(t,e)=>{sc.init(t,e);let r=t._zod.parse;ke(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=Vo(()=>{let s=e.options,o=new Map;for(let i of s){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(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});t._zod.parse=(s,o)=>{let i=s.value;if(!Us(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),jp=w("$ZodIntersection",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,o=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>qv(r,c,u)):qv(r,o,i)}});zp=w("$ZodRecord",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Hs(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let o=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:s[c],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...kr(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...kr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(s)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>ir(u,n,It())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...kr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...kr(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),Lp=w("$ZodEnum",(t,e)=>{xe.init(t,e);let r=qo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Bd.has(typeof n)).map(n=>typeof n=="string"?on(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),Fp=w("$ZodLiteral",(t,e)=>{xe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?on(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),Up=w("$ZodTransform",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Mr;return r.value=s,r}}),Hp=w("$ZodOptional",(t,e)=>{xe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Go(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Zp=w("$ZodNullable",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Go(r.source)}|null)$`):void 0}),ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Bp=w("$ZodDefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Vv(o,e)):Vv(s,e)}});qp=w("$ZodPrefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Vp=w("$ZodNonOptional",(t,e)=>{xe.init(t,e),ke(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Wv(o,t)):Wv(s,t)}});Wp=w("$ZodCatch",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>ir(i,n,It()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>ir(o,n,It()))},input:r.value}),r.issues=[]),r)}}),Gp=w("$ZodPipe",(t,e)=>{xe.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Gv(o,e,n)):Gv(s,e,n)}});Kp=w("$ZodReadonly",(t,e)=>{xe.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Kv):Kv(s)}});Jp=w("$ZodCustom",(t,e)=>{Ye.init(t,e),xe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Jv(o,r,n,t));Jv(s,r,n,t)}})});function nb(){return{localeError:yO()}}var gO,yO,sb=b(()=>{wr();gO=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},yO=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${gO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ka(n.values[0])}`:`Invalid option: expected one of ${Wa(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Wa(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var oc=b(()=>{});function ob(){return new Qo}var Qo,an,Xp=b(()=>{Qo=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};an=ob()});function Qp(t,e){return new t({type:"string",...G(e)})}function em(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...G(e)})}function ic(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...G(e)})}function tm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...G(e)})}function rm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(e)})}function nm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(e)})}function sm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(e)})}function om(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...G(e)})}function im(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...G(e)})}function am(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(e)})}function cm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...G(e)})}function um(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(e)})}function lm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...G(e)})}function dm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...G(e)})}function pm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(e)})}function mm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(e)})}function fm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(e)})}function hm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(e)})}function gm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(e)})}function ym(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...G(e)})}function _m(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...G(e)})}function xm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...G(e)})}function vm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...G(e)})}function ib(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(e)})}function ab(t,e){return new t({type:"string",format:"date",check:"string_format",...G(e)})}function cb(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...G(e)})}function ub(t,e){return new t({type:"string",format:"duration",check:"string_format",...G(e)})}function bm(t,e){return new t({type:"number",checks:[],...G(e)})}function Sm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...G(e)})}function km(t,e){return new t({type:"boolean",...G(e)})}function wm(t,e){return new t({type:"null",...G(e)})}function Em(t){return new t({type:"unknown"})}function $m(t,e){return new t({type:"never",...G(e)})}function ac(t,e){return new ip({check:"less_than",...G(e),value:t,inclusive:!1})}function ei(t,e){return new ip({check:"less_than",...G(e),value:t,inclusive:!0})}function cc(t,e){return new ap({check:"greater_than",...G(e),value:t,inclusive:!1})}function ti(t,e){return new ap({check:"greater_than",...G(e),value:t,inclusive:!0})}function uc(t,e){return new Pv({check:"multiple_of",...G(e),value:t})}function lc(t,e){return new Cv({check:"max_length",...G(e),maximum:t})}function Zs(t,e){return new Ov({check:"min_length",...G(e),minimum:t})}function dc(t,e){return new Iv({check:"length_equals",...G(e),length:t})}function Tm(t,e){return new Av({check:"string_format",format:"regex",...G(e),pattern:t})}function Pm(t){return new Nv({check:"string_format",format:"lowercase",...G(t)})}function Rm(t){return new Dv({check:"string_format",format:"uppercase",...G(t)})}function Cm(t,e){return new Mv({check:"string_format",format:"includes",...G(e),includes:t})}function Om(t,e){return new jv({check:"string_format",format:"starts_with",...G(e),prefix:t})}function Im(t,e){return new zv({check:"string_format",format:"ends_with",...G(e),suffix:t})}function es(t){return new Lv({check:"overwrite",tx:t})}function Am(t){return es(e=>e.normalize(t))}function Nm(){return es(t=>t.trim())}function Dm(){return es(t=>t.toLowerCase())}function Mm(){return es(t=>t.toUpperCase())}function lb(t,e,r){return new t({type:"array",element:e,...G(r)})}function jm(t,e,r){let n=G(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function zm(t,e,r){return new t({type:"custom",check:"custom",fn:e,...G(r)})}var db=b(()=>{Qa();wr()});var pb=b(()=>{});function Lm(t,e){if(t instanceof Qo){let n=new pc(e),s={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,u]=a;o[c]=n.emit(u,{...e,external:i})}if(Object.keys(s).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let r=new pc(e);return r.process(t),r.emit(t,e)}function Ve(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let s=t._zod.def;switch(s.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 Ve(s.element,r);case"object":{for(let o in s.shape)if(Ve(s.shape[o],r))return!0;return!1}case"union":{for(let o of s.options)if(Ve(o,r))return!0;return!1}case"intersection":return Ve(s.left,r)||Ve(s.right,r);case"tuple":{for(let o of s.items)if(Ve(o,r))return!0;return!!(s.rest&&Ve(s.rest,r))}case"record":return Ve(s.keyType,r)||Ve(s.valueType,r);case"map":return Ve(s.keyType,r)||Ve(s.valueType,r);case"set":return Ve(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ve(s.innerType,r);case"lazy":return Ve(s.getter(),r);case"default":return Ve(s.innerType,r);case"prefault":return Ve(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ve(s.in,r)||Ve(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var pc,mb=b(()=>{Xp();wr();pc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??an,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,l),this.seen.get(p).isParent=!0;else{let f=a.schema;switch(s.type){case"string":{let m=f;m.type="string";let{minimum:h,maximum:g,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),_&&(m.format=o[_]??_,m.format===""&&delete m.format),y&&(m.contentEncoding=y),v&&v.size>0){let x=[...v];x.length===1?m.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{let m=f,{minimum:h,maximum:g,format:_,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?m.type="integer":m.type="number",typeof x=="number"&&(m.exclusiveMinimum=x),typeof h=="number"&&(m.minimum=h,typeof x=="number"&&(x>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof y=="number"&&(m.exclusiveMaximum=y),typeof g=="number"&&(m.maximum=g,typeof y=="number"&&(y<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof v=="number"&&(m.multipleOf=v);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(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let h=s.shape;for(let v in h)m.properties[v]=this.process(h[v],{...l,path:[...l.path,"properties",v]});let g=new Set(Object.keys(h)),_=new Set([...g].filter(v=>{let y=s.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));_.size>0&&(m.required=Array.from(_)),s.catchall?._zod.def.type==="never"?m.additionalProperties=!1:s.catchall?s.catchall&&(m.additionalProperties=this.process(s.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=s.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let m=f,h=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(h)?h.allOf:[h],..._(g)?g.allOf:[g]];m.allOf=v;break}case"tuple":{let m=f;m.type="array";let h=s.items.map((v,y)=>this.process(v,{...l,path:[...l.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,s.rest){let v=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?m.items=v:m.additionalItems=v}s.rest&&(m.items=this.process(s.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof _=="number"&&(m.maxItems=_);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(s.keyType,{...l,path:[...l.path,"propertyNames"]}),m.additionalProperties=this.process(s.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=f,h=qo(s.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 s.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:_,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),_!==void 0&&(h.maxLength=_),v?v.length===1?(h.contentMediaType=v[0],Object.assign(m,h)):m.anyOf=v.map(y=>({...h,contentMediaType:y})):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(s.innerType,l);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let m;try{m=s.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"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(m,l),a.ref=m;break}case"readonly":{this.process(s.innerType,l),a.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,l),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,l),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"&&Ve(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let _=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=_,{defId:_,ref:`${g("__shared")}#/${l}/${_}`}}if(d[1]===s)return{ref:"#"};let f=`#/${l}/`,m=d[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:p,defId:f}=o(d);l.def={...l.schema},f&&(l.defId=f);let m=l.schema;for(let h in m)delete m[h];m.$ref=p};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
59
59
 
60
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let p=this.seen.get(d),f=p.def??p.schema,m={...f};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,m))}p.isParent||this.override({zodSchema:d,jsonSchema:f,path:p.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,s.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var mb=b(()=>{});var dt=b(()=>{Fs();tp();Gd();tb();Xa();ap();wr();Ya();sc();Jp();ip();db();lb();pb();mb()});var zm=b(()=>{dt()});function Lm(t,e){let r={type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},...ce.normalizeParams(e)};return new KO(r)}var GO,KO,fb=b(()=>{dt();dt();zm();GO=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");xe.init(t,e),t.def=e,t.parse=(r,n)=>Jd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Yn(t,r,n),t.parseAsync=async(r,n)=>Xd(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Xn(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>At(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),KO=w("ZodMiniObject",(t,e)=>{rc.init(t,e),GO.init(t,e),ce.defineLazy(t,"shape",()=>e.shape)})});var hb=b(()=>{});var gb=b(()=>{});var yb=b(()=>{});var _b=b(()=>{dt();zm();fb();hb();dt();sc();gb();yb()});var xb=b(()=>{_b()});var Fm=b(()=>{xb()});function qt(t){return!!t._zod}function ts(t){let e=Object.values(t);if(e.length===0)return Lm({});let r=e.every(qt),n=e.every(s=>!qt(s));if(r)return Lm(t);if(n)return Dd(t);throw new Error("Mixed Zod versions detected in object shape.")}function cn(t,e){return qt(t)?Yn(t,e):t.safeParse(e)}async function pc(t,e){return qt(t)?await Xn(t,e):await t.safeParseAsync(e)}function un(t){if(!t)return;let e;if(qt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Bs(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return ts(t)}}if(qt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function mc(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 bb(t){return t.description}function Sb(t){if(qt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function fc(t){if(qt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var ti=b(()=>{Ho();Fm()});var Um=b(()=>{dt()});var ri={};Le(ri,{ZodISODate:()=>wb,ZodISODateTime:()=>kb,ZodISODuration:()=>$b,ZodISOTime:()=>Eb,date:()=>Zm,datetime:()=>Hm,duration:()=>qm,time:()=>Bm});function Hm(t){return ob(kb,t)}function Zm(t){return ib(wb,t)}function Bm(t){return ab(Eb,t)}function qm(t){return cb($b,t)}var kb,wb,Eb,$b,Vm=b(()=>{dt();Wm();kb=w("ZodISODateTime",(t,e)=>{Jv.init(t,e),Ie.init(t,e)});wb=w("ZodISODate",(t,e)=>{Yv.init(t,e),Ie.init(t,e)});Eb=w("ZodISOTime",(t,e)=>{Xv.init(t,e),Ie.init(t,e)});$b=w("ZodISODuration",(t,e)=>{Qv.init(t,e),Ie.init(t,e)})});var Tb,Hq,ni,Gm=b(()=>{dt();dt();Tb=(t,e)=>{Ka.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Wd(t,r)},flatten:{value:r=>Vd(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Hq=w("ZodError",Tb),ni=w("ZodError",Tb,{Parent:Error})});var Pb,Rb,Cb,Ob,Km=b(()=>{dt();Gm();Pb=Kd(ni),Rb=Yd(ni),Cb=Qd(ni),Ob=ep(ni)});function S(t){return Yp(oI,t)}function ge(t){return xm(Mb,t)}function Ab(t){return vm(kI,t)}function Ge(t){return bm(wI,t)}function jb(t){return Sm(EI,t)}function Ae(){return km($I)}function PI(t){return wm(TI,t)}function le(t,e){return ub(RI,t,e)}function z(t,e){let r={type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},...ce.normalizeParams(e)};return new zb(r)}function pt(t,e){return new zb({type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},catchall:Ae(),...ce.normalizeParams(e)})}function Te(t,e){return new Lb({type:"union",options:t,...ce.normalizeParams(e)})}function Xm(t,e,r){return new CI({type:"union",options:e,discriminator:t,...ce.normalizeParams(r)})}function gc(t,e){return new OI({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new II({type:"record",keyType:t,valueType:e,...ce.normalizeParams(r)})}function kt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Jm({type:"enum",entries:r,...ce.normalizeParams(e)})}function Z(t,e){return new AI({type:"literal",values:Array.isArray(t)?t:[t],...ce.normalizeParams(e)})}function Fb(t){return new NI({type:"transform",transform:t})}function Ne(t){return new Ub({type:"optional",innerType:t})}function Nb(t){return new DI({type:"nullable",innerType:t})}function jI(t,e){return new MI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function LI(t,e){return new zI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function FI(t,e){return new Hb({type:"nonoptional",innerType:t,...ce.normalizeParams(e)})}function HI(t,e){return new UI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Ym(t,e){return new ZI({type:"pipe",in:t,out:e})}function qI(t){return new BI({type:"readonly",innerType:t})}function VI(t){let e=new Ye({check:"custom"});return e._zod.check=t,e}function Bb(t,e){return Dm(Zb,t??(()=>!0),e)}function WI(t,e={}){return Mm(Zb,t,e)}function GI(t){let e=VI(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ce.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(ce.issue(s))}},t(r.value,r)));return e}function Qm(t,e){return Ym(Fb(t),e)}var je,Db,oI,Ie,iI,Ib,hc,aI,cI,uI,lI,dI,pI,mI,fI,hI,gI,yI,_I,xI,vI,bI,SI,Mb,kI,wI,EI,$I,TI,RI,zb,Lb,CI,OI,II,Jm,AI,NI,Ub,DI,MI,zI,Hb,UI,ZI,BI,Zb,Wm=b(()=>{dt();dt();Um();Vm();Km();je=w("ZodType",(t,e)=>(xe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>At(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Pb(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Cb(t,r,n),t.parseAsync=async(r,n)=>Rb(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ob(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(WI(r,n)),t.superRefine=r=>t.check(GI(r)),t.overwrite=r=>t.check(Qn(r)),t.optional=()=>Ne(t),t.nullable=()=>Nb(t),t.nullish=()=>Ne(Nb(t)),t.nonoptional=r=>FI(t,r),t.array=()=>le(t),t.or=r=>Te([t,r]),t.and=r=>gc(t,r),t.transform=r=>Ym(t,Fb(r)),t.default=r=>jI(t,r),t.prefault=r=>LI(t,r),t.catch=r=>HI(t,r),t.pipe=r=>Ym(t,r),t.readonly=()=>qI(t),t.describe=r=>{let n=t.clone();return an.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return an.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return an.get(t);let n=t.clone();return an.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Db=w("_ZodString",(t,e)=>{Yo.init(t,e),je.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Em(...n)),t.includes=(...n)=>t.check(Pm(...n)),t.startsWith=(...n)=>t.check(Rm(...n)),t.endsWith=(...n)=>t.check(Cm(...n)),t.min=(...n)=>t.check(Zs(...n)),t.max=(...n)=>t.check(uc(...n)),t.length=(...n)=>t.check(lc(...n)),t.nonempty=(...n)=>t.check(Zs(1,...n)),t.lowercase=n=>t.check($m(n)),t.uppercase=n=>t.check(Tm(n)),t.trim=()=>t.check(Im()),t.normalize=(...n)=>t.check(Om(...n)),t.toLowerCase=()=>t.check(Am()),t.toUpperCase=()=>t.check(Nm())}),oI=w("ZodString",(t,e)=>{Yo.init(t,e),Db.init(t,e),t.email=r=>t.check(Xp(iI,r)),t.url=r=>t.check(nm(aI,r)),t.jwt=r=>t.check(_m(SI,r)),t.emoji=r=>t.check(sm(cI,r)),t.guid=r=>t.check(oc(Ib,r)),t.uuid=r=>t.check(Qp(hc,r)),t.uuidv4=r=>t.check(em(hc,r)),t.uuidv6=r=>t.check(tm(hc,r)),t.uuidv7=r=>t.check(rm(hc,r)),t.nanoid=r=>t.check(om(uI,r)),t.guid=r=>t.check(oc(Ib,r)),t.cuid=r=>t.check(im(lI,r)),t.cuid2=r=>t.check(am(dI,r)),t.ulid=r=>t.check(cm(pI,r)),t.base64=r=>t.check(hm(xI,r)),t.base64url=r=>t.check(gm(vI,r)),t.xid=r=>t.check(um(mI,r)),t.ksuid=r=>t.check(lm(fI,r)),t.ipv4=r=>t.check(dm(hI,r)),t.ipv6=r=>t.check(pm(gI,r)),t.cidrv4=r=>t.check(mm(yI,r)),t.cidrv6=r=>t.check(fm(_I,r)),t.e164=r=>t.check(ym(bI,r)),t.datetime=r=>t.check(Hm(r)),t.date=r=>t.check(Zm(r)),t.time=r=>t.check(Bm(r)),t.duration=r=>t.check(qm(r))});Ie=w("ZodStringFormat",(t,e)=>{we.init(t,e),Db.init(t,e)}),iI=w("ZodEmail",(t,e)=>{dp.init(t,e),Ie.init(t,e)}),Ib=w("ZodGUID",(t,e)=>{up.init(t,e),Ie.init(t,e)}),hc=w("ZodUUID",(t,e)=>{lp.init(t,e),Ie.init(t,e)}),aI=w("ZodURL",(t,e)=>{pp.init(t,e),Ie.init(t,e)}),cI=w("ZodEmoji",(t,e)=>{mp.init(t,e),Ie.init(t,e)}),uI=w("ZodNanoID",(t,e)=>{fp.init(t,e),Ie.init(t,e)}),lI=w("ZodCUID",(t,e)=>{hp.init(t,e),Ie.init(t,e)}),dI=w("ZodCUID2",(t,e)=>{gp.init(t,e),Ie.init(t,e)}),pI=w("ZodULID",(t,e)=>{yp.init(t,e),Ie.init(t,e)}),mI=w("ZodXID",(t,e)=>{_p.init(t,e),Ie.init(t,e)}),fI=w("ZodKSUID",(t,e)=>{xp.init(t,e),Ie.init(t,e)}),hI=w("ZodIPv4",(t,e)=>{vp.init(t,e),Ie.init(t,e)}),gI=w("ZodIPv6",(t,e)=>{bp.init(t,e),Ie.init(t,e)}),yI=w("ZodCIDRv4",(t,e)=>{Sp.init(t,e),Ie.init(t,e)}),_I=w("ZodCIDRv6",(t,e)=>{kp.init(t,e),Ie.init(t,e)}),xI=w("ZodBase64",(t,e)=>{wp.init(t,e),Ie.init(t,e)}),vI=w("ZodBase64URL",(t,e)=>{Ep.init(t,e),Ie.init(t,e)}),bI=w("ZodE164",(t,e)=>{$p.init(t,e),Ie.init(t,e)}),SI=w("ZodJWT",(t,e)=>{Tp.init(t,e),Ie.init(t,e)}),Mb=w("ZodNumber",(t,e)=>{tc.init(t,e),je.init(t,e),t.gt=(n,s)=>t.check(ac(n,s)),t.gte=(n,s)=>t.check(ei(n,s)),t.min=(n,s)=>t.check(ei(n,s)),t.lt=(n,s)=>t.check(ic(n,s)),t.lte=(n,s)=>t.check(Qo(n,s)),t.max=(n,s)=>t.check(Qo(n,s)),t.int=n=>t.check(Ab(n)),t.safe=n=>t.check(Ab(n)),t.positive=n=>t.check(ac(0,n)),t.nonnegative=n=>t.check(ei(0,n)),t.negative=n=>t.check(ic(0,n)),t.nonpositive=n=>t.check(Qo(0,n)),t.multipleOf=(n,s)=>t.check(cc(n,s)),t.step=(n,s)=>t.check(cc(n,s)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});kI=w("ZodNumberFormat",(t,e)=>{Pp.init(t,e),Mb.init(t,e)});wI=w("ZodBoolean",(t,e)=>{Rp.init(t,e),je.init(t,e)});EI=w("ZodNull",(t,e)=>{Cp.init(t,e),je.init(t,e)});$I=w("ZodUnknown",(t,e)=>{Op.init(t,e),je.init(t,e)});TI=w("ZodNever",(t,e)=>{Ip.init(t,e),je.init(t,e)});RI=w("ZodArray",(t,e)=>{Ap.init(t,e),je.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Zs(r,n)),t.nonempty=r=>t.check(Zs(1,r)),t.max=(r,n)=>t.check(uc(r,n)),t.length=(r,n)=>t.check(lc(r,n)),t.unwrap=()=>t.element});zb=w("ZodObject",(t,e)=>{rc.init(t,e),je.init(t,e),ce.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>kt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ae()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ae()}),t.strict=()=>t.clone({...t._zod.def,catchall:PI()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ce.extend(t,r),t.merge=r=>ce.merge(t,r),t.pick=r=>ce.pick(t,r),t.omit=r=>ce.omit(t,r),t.partial=(...r)=>ce.partial(Ub,t,r[0]),t.required=(...r)=>ce.required(Hb,t,r[0])});Lb=w("ZodUnion",(t,e)=>{nc.init(t,e),je.init(t,e),t.options=e.options});CI=w("ZodDiscriminatedUnion",(t,e)=>{Lb.init(t,e),Np.init(t,e)});OI=w("ZodIntersection",(t,e)=>{Dp.init(t,e),je.init(t,e)});II=w("ZodRecord",(t,e)=>{Mp.init(t,e),je.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Jm=w("ZodEnum",(t,e)=>{jp.init(t,e),je.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Jm({...e,checks:[],...ce.normalizeParams(s),entries:o})},t.exclude=(n,s)=>{let o={...e.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Jm({...e,checks:[],...ce.normalizeParams(s),entries:o})}});AI=w("ZodLiteral",(t,e)=>{zp.init(t,e),je.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]}})});NI=w("ZodTransform",(t,e)=>{Lp.init(t,e),je.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ce.issue(o,r.value,e));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ce.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});Ub=w("ZodOptional",(t,e)=>{Fp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});DI=w("ZodNullable",(t,e)=>{Up.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});MI=w("ZodDefault",(t,e)=>{Hp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});zI=w("ZodPrefault",(t,e)=>{Zp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});Hb=w("ZodNonOptional",(t,e)=>{Bp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});UI=w("ZodCatch",(t,e)=>{qp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});ZI=w("ZodPipe",(t,e)=>{Vp.init(t,e),je.init(t,e),t.in=e.in,t.out=e.out});BI=w("ZodReadonly",(t,e)=>{Wp.init(t,e),je.init(t,e)});Zb=w("ZodCustom",(t,e)=>{Gp.init(t,e),je.init(t,e)})});var qb=b(()=>{});var Vb=b(()=>{});var Wb=b(()=>{dt();Wm();Um();Gm();Km();qb();dt();nb();sc();Vm();Vb();It(rb())});var Gb=b(()=>{Wb()});var Kb=b(()=>{Gb()});function pS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function mS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var tf,Jb,ln,_c,We,Yb,Xb,s4,YI,XI,rf,Nt,si,Qb,Xe,Vt,Wt,Qe,xc,eS,nf,tS,rS,sf,oi,V,of,nS,sS,o4,vc,QI,bc,eA,ii,qs,oS,tA,rA,nA,sA,oA,iA,af,aA,cA,cf,Sc,uA,lA,kc,dA,ai,ci,pA,ui,Vs,mA,li,wc,Ec,$c,i4,Tc,Pc,Rc,iS,aS,cS,uf,uS,di,Ws,lS,fA,Gs,hA,Ks,gA,lf,yA,Cc,_A,xA,vA,bA,SA,kA,wA,EA,$A,TA,Js,PA,RA,Oc,df,pf,mf,CA,OA,IA,ff,AA,NA,DA,MA,jA,dS,Ic,zA,Ac,a4,LA,Ys,FA,c4,pi,UA,hf,HA,ZA,BA,qA,VA,WA,GA,yc,KA,JA,YA,mi,gf,XA,QA,eN,tN,rN,nN,sN,oN,iN,aN,cN,uN,lN,dN,pN,mN,fN,hN,Xs,gN,yN,_N,Nc,xN,vN,bN,yf,SN,u4,l4,d4,p4,m4,f4,H,ef,rs=b(()=>{Kb();tf="2025-11-25",Jb=[tf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ln="io.modelcontextprotocol/related-task",_c="2.0",We=Bb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Yb=Te([S(),ge().int()]),Xb=S(),s4=pt({ttl:ge().optional(),pollInterval:ge().optional()}),YI=z({ttl:ge().optional()}),XI=z({taskId:S()}),rf=pt({progressToken:Yb.optional(),[ln]:XI.optional()}),Nt=z({_meta:rf.optional()}),si=Nt.extend({task:YI.optional()}),Qb=t=>si.safeParse(t).success,Xe=z({method:S(),params:Nt.loose().optional()}),Vt=z({_meta:rf.optional()}),Wt=z({method:S(),params:Vt.loose().optional()}),Qe=pt({_meta:rf.optional()}),xc=Te([S(),ge().int()]),eS=z({jsonrpc:Z(_c),id:xc,...Xe.shape}).strict(),nf=t=>eS.safeParse(t).success,tS=z({jsonrpc:Z(_c),...Wt.shape}).strict(),rS=t=>tS.safeParse(t).success,sf=z({jsonrpc:Z(_c),id:xc,result:Qe}).strict(),oi=t=>sf.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"})(V||(V={}));of=z({jsonrpc:Z(_c),id:xc.optional(),error:z({code:ge().int(),message:S(),data:Ae().optional()})}).strict(),nS=t=>of.safeParse(t).success,sS=Te([eS,tS,sf,of]),o4=Te([sf,of]),vc=Qe.strict(),QI=Vt.extend({requestId:xc.optional(),reason:S().optional()}),bc=Wt.extend({method:Z("notifications/cancelled"),params:QI}),eA=z({src:S(),mimeType:S().optional(),sizes:le(S()).optional(),theme:kt(["light","dark"]).optional()}),ii=z({icons:le(eA).optional()}),qs=z({name:S(),title:S().optional()}),oS=qs.extend({...qs.shape,...ii.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),tA=gc(z({applyDefaults:Ge().optional()}),Ee(S(),Ae())),rA=Qm(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,gc(z({form:tA.optional(),url:We.optional()}),Ee(S(),Ae()).optional())),nA=pt({list:We.optional(),cancel:We.optional(),requests:pt({sampling:pt({createMessage:We.optional()}).optional(),elicitation:pt({create:We.optional()}).optional()}).optional()}),sA=pt({list:We.optional(),cancel:We.optional(),requests:pt({tools:pt({call:We.optional()}).optional()}).optional()}),oA=z({experimental:Ee(S(),We).optional(),sampling:z({context:We.optional(),tools:We.optional()}).optional(),elicitation:rA.optional(),roots:z({listChanged:Ge().optional()}).optional(),tasks:nA.optional(),extensions:Ee(S(),We).optional()}),iA=Nt.extend({protocolVersion:S(),capabilities:oA,clientInfo:oS}),af=Xe.extend({method:Z("initialize"),params:iA}),aA=z({experimental:Ee(S(),We).optional(),logging:We.optional(),completions:We.optional(),prompts:z({listChanged:Ge().optional()}).optional(),resources:z({subscribe:Ge().optional(),listChanged:Ge().optional()}).optional(),tools:z({listChanged:Ge().optional()}).optional(),tasks:sA.optional(),extensions:Ee(S(),We).optional()}),cA=Qe.extend({protocolVersion:S(),capabilities:aA,serverInfo:oS,instructions:S().optional()}),cf=Wt.extend({method:Z("notifications/initialized"),params:Vt.optional()}),Sc=Xe.extend({method:Z("ping"),params:Nt.optional()}),uA=z({progress:ge(),total:Ne(ge()),message:Ne(S())}),lA=z({...Vt.shape,...uA.shape,progressToken:Yb}),kc=Wt.extend({method:Z("notifications/progress"),params:lA}),dA=Nt.extend({cursor:Xb.optional()}),ai=Xe.extend({params:dA.optional()}),ci=Qe.extend({nextCursor:Xb.optional()}),pA=kt(["working","input_required","completed","failed","cancelled"]),ui=z({taskId:S(),status:pA,ttl:Te([ge(),jb()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ne(ge()),statusMessage:Ne(S())}),Vs=Qe.extend({task:ui}),mA=Vt.merge(ui),li=Wt.extend({method:Z("notifications/tasks/status"),params:mA}),wc=Xe.extend({method:Z("tasks/get"),params:Nt.extend({taskId:S()})}),Ec=Qe.merge(ui),$c=Xe.extend({method:Z("tasks/result"),params:Nt.extend({taskId:S()})}),i4=Qe.loose(),Tc=ai.extend({method:Z("tasks/list")}),Pc=ci.extend({tasks:le(ui)}),Rc=Xe.extend({method:Z("tasks/cancel"),params:Nt.extend({taskId:S()})}),iS=Qe.merge(ui),aS=z({uri:S(),mimeType:Ne(S()),_meta:Ee(S(),Ae()).optional()}),cS=aS.extend({text:S()}),uf=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),uS=aS.extend({blob:uf}),di=kt(["user","assistant"]),Ws=z({audience:le(di).optional(),priority:ge().min(0).max(1).optional(),lastModified:ri.datetime({offset:!0}).optional()}),lS=z({...qs.shape,...ii.shape,uri:S(),description:Ne(S()),mimeType:Ne(S()),size:Ne(ge()),annotations:Ws.optional(),_meta:Ne(pt({}))}),fA=z({...qs.shape,...ii.shape,uriTemplate:S(),description:Ne(S()),mimeType:Ne(S()),annotations:Ws.optional(),_meta:Ne(pt({}))}),Gs=ai.extend({method:Z("resources/list")}),hA=ci.extend({resources:le(lS)}),Ks=ai.extend({method:Z("resources/templates/list")}),gA=ci.extend({resourceTemplates:le(fA)}),lf=Nt.extend({uri:S()}),yA=lf,Cc=Xe.extend({method:Z("resources/read"),params:yA}),_A=Qe.extend({contents:le(Te([cS,uS]))}),xA=Wt.extend({method:Z("notifications/resources/list_changed"),params:Vt.optional()}),vA=lf,bA=Xe.extend({method:Z("resources/subscribe"),params:vA}),SA=lf,kA=Xe.extend({method:Z("resources/unsubscribe"),params:SA}),wA=Vt.extend({uri:S()}),EA=Wt.extend({method:Z("notifications/resources/updated"),params:wA}),$A=z({name:S(),description:Ne(S()),required:Ne(Ge())}),TA=z({...qs.shape,...ii.shape,description:Ne(S()),arguments:Ne(le($A)),_meta:Ne(pt({}))}),Js=ai.extend({method:Z("prompts/list")}),PA=ci.extend({prompts:le(TA)}),RA=Nt.extend({name:S(),arguments:Ee(S(),S()).optional()}),Oc=Xe.extend({method:Z("prompts/get"),params:RA}),df=z({type:Z("text"),text:S(),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),pf=z({type:Z("image"),data:uf,mimeType:S(),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),mf=z({type:Z("audio"),data:uf,mimeType:S(),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),CA=z({type:Z("tool_use"),name:S(),id:S(),input:Ee(S(),Ae()),_meta:Ee(S(),Ae()).optional()}),OA=z({type:Z("resource"),resource:Te([cS,uS]),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),IA=lS.extend({type:Z("resource_link")}),ff=Te([df,pf,mf,IA,OA]),AA=z({role:di,content:ff}),NA=Qe.extend({description:S().optional(),messages:le(AA)}),DA=Wt.extend({method:Z("notifications/prompts/list_changed"),params:Vt.optional()}),MA=z({title:S().optional(),readOnlyHint:Ge().optional(),destructiveHint:Ge().optional(),idempotentHint:Ge().optional(),openWorldHint:Ge().optional()}),jA=z({taskSupport:kt(["required","optional","forbidden"]).optional()}),dS=z({...qs.shape,...ii.shape,description:S().optional(),inputSchema:z({type:Z("object"),properties:Ee(S(),We).optional(),required:le(S()).optional()}).catchall(Ae()),outputSchema:z({type:Z("object"),properties:Ee(S(),We).optional(),required:le(S()).optional()}).catchall(Ae()).optional(),annotations:MA.optional(),execution:jA.optional(),_meta:Ee(S(),Ae()).optional()}),Ic=ai.extend({method:Z("tools/list")}),zA=ci.extend({tools:le(dS)}),Ac=Qe.extend({content:le(ff).default([]),structuredContent:Ee(S(),Ae()).optional(),isError:Ge().optional()}),a4=Ac.or(Qe.extend({toolResult:Ae()})),LA=si.extend({name:S(),arguments:Ee(S(),Ae()).optional()}),Ys=Xe.extend({method:Z("tools/call"),params:LA}),FA=Wt.extend({method:Z("notifications/tools/list_changed"),params:Vt.optional()}),c4=z({autoRefresh:Ge().default(!0),debounceMs:ge().int().nonnegative().default(300)}),pi=kt(["debug","info","notice","warning","error","critical","alert","emergency"]),UA=Nt.extend({level:pi}),hf=Xe.extend({method:Z("logging/setLevel"),params:UA}),HA=Vt.extend({level:pi,logger:S().optional(),data:Ae()}),ZA=Wt.extend({method:Z("notifications/message"),params:HA}),BA=z({name:S().optional()}),qA=z({hints:le(BA).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),VA=z({mode:kt(["auto","required","none"]).optional()}),WA=z({type:Z("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:le(ff).default([]),structuredContent:z({}).loose().optional(),isError:Ge().optional(),_meta:Ee(S(),Ae()).optional()}),GA=Xm("type",[df,pf,mf]),yc=Xm("type",[df,pf,mf,CA,WA]),KA=z({role:di,content:Te([yc,le(yc)]),_meta:Ee(S(),Ae()).optional()}),JA=si.extend({messages:le(KA),modelPreferences:qA.optional(),systemPrompt:S().optional(),includeContext:kt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:le(S()).optional(),metadata:We.optional(),tools:le(dS).optional(),toolChoice:VA.optional()}),YA=Xe.extend({method:Z("sampling/createMessage"),params:JA}),mi=Qe.extend({model:S(),stopReason:Ne(kt(["endTurn","stopSequence","maxTokens"]).or(S())),role:di,content:GA}),gf=Qe.extend({model:S(),stopReason:Ne(kt(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:di,content:Te([yc,le(yc)])}),XA=z({type:Z("boolean"),title:S().optional(),description:S().optional(),default:Ge().optional()}),QA=z({type:Z("string"),title:S().optional(),description:S().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:kt(["email","uri","date","date-time"]).optional(),default:S().optional()}),eN=z({type:kt(["number","integer"]),title:S().optional(),description:S().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),tN=z({type:Z("string"),title:S().optional(),description:S().optional(),enum:le(S()),default:S().optional()}),rN=z({type:Z("string"),title:S().optional(),description:S().optional(),oneOf:le(z({const:S(),title:S()})),default:S().optional()}),nN=z({type:Z("string"),title:S().optional(),description:S().optional(),enum:le(S()),enumNames:le(S()).optional(),default:S().optional()}),sN=Te([tN,rN]),oN=z({type:Z("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({type:Z("string"),enum:le(S())}),default:le(S()).optional()}),iN=z({type:Z("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({anyOf:le(z({const:S(),title:S()}))}),default:le(S()).optional()}),aN=Te([oN,iN]),cN=Te([nN,sN,aN]),uN=Te([cN,XA,QA,eN]),lN=si.extend({mode:Z("form").optional(),message:S(),requestedSchema:z({type:Z("object"),properties:Ee(S(),uN),required:le(S()).optional()})}),dN=si.extend({mode:Z("url"),message:S(),elicitationId:S(),url:S().url()}),pN=Te([lN,dN]),mN=Xe.extend({method:Z("elicitation/create"),params:pN}),fN=Vt.extend({elicitationId:S()}),hN=Wt.extend({method:Z("notifications/elicitation/complete"),params:fN}),Xs=Qe.extend({action:kt(["accept","decline","cancel"]),content:Qm(t=>t===null?void 0:t,Ee(S(),Te([S(),ge(),Ge(),le(S())])).optional())}),gN=z({type:Z("ref/resource"),uri:S()}),yN=z({type:Z("ref/prompt"),name:S()}),_N=Nt.extend({ref:Te([yN,gN]),argument:z({name:S(),value:S()}),context:z({arguments:Ee(S(),S()).optional()}).optional()}),Nc=Xe.extend({method:Z("completion/complete"),params:_N});xN=Qe.extend({completion:pt({values:le(S()).max(100),total:Ne(ge().int()),hasMore:Ne(Ge())})}),vN=z({uri:S().startsWith("file://"),name:S().optional(),_meta:Ee(S(),Ae()).optional()}),bN=Xe.extend({method:Z("roots/list"),params:Nt.optional()}),yf=Qe.extend({roots:le(vN)}),SN=Wt.extend({method:Z("notifications/roots/list_changed"),params:Vt.optional()}),u4=Te([Sc,af,Nc,hf,Oc,Js,Gs,Ks,Cc,bA,kA,Ys,Ic,wc,$c,Tc,Rc]),l4=Te([bc,kc,cf,SN,li]),d4=Te([vc,mi,gf,Xs,yf,Ec,Pc,Vs]),p4=Te([Sc,YA,mN,bN,wc,$c,Tc,Rc]),m4=Te([bc,kc,ZA,EA,xA,FA,DA,li,hN]),f4=Te([vc,cA,xN,NA,PA,hA,gA,_A,Ac,zA,Ec,Pc,Vs]),H=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===V.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new ef(s.elicitations,r)}return new t(e,r,n)}},ef=class extends H{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(V.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function dn(t){return t==="completed"||t==="failed"||t==="cancelled"}var fS=b(()=>{});var gS,hS,yS,Dc=b(()=>{gS=Symbol("Let zodToJsonSchema decide on which parser to use"),hS={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"},yS=t=>typeof t=="string"?{...hS,name:t}:{...hS,...t}});var _S,_f=b(()=>{Dc();_S=t=>{let e=yS(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function xf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,s){t[e]=r,xf(t,e,n,s)}var pn=b(()=>{});var Mc,jc=b(()=>{Mc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function De(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Mc(e,t.currentPath):e.join("/")}}var Gt=b(()=>{jc()});function xS(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==I.ZodAny&&(r.items=J(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var vf=b(()=>{Ho();pn();Be()});function vS(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var bf=b(()=>{pn()});function bS(){return{type:"boolean"}}var Sf=b(()=>{});function zc(t,e){return J(t.type._def,e)}var Lc=b(()=>{Be()});var SS,kf=b(()=>{Be();SS=(t,e)=>J(t.innerType._def,e)});function wf(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>wf(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return kN(t,e)}}var kN,Ef=b(()=>{pn();kN=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function kS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var $f=b(()=>{Be()});function wS(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):De(e)}var Tf=b(()=>{Be();Gt()});function ES(t){return{type:"string",enum:Array.from(t.values)}}var Pf=b(()=>{});function $S(t,e){let r=[J(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(wN(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var wN,Rf=b(()=>{Be();wN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function TS(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Cf=b(()=>{});function Fc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":cr(r,"email",n.message,e);break;case"format:idn-email":cr(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,ar.email,n.message,e);break}break;case"url":cr(r,"uri",n.message,e);break;case"uuid":cr(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,ar.cuid,n.message,e);break;case"cuid2":mt(r,ar.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${If(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${If(n.value,e)}$`),n.message,e);break;case"datetime":cr(r,"date-time",n.message,e);break;case"date":cr(r,"date",n.message,e);break;case"time":cr(r,"time",n.message,e);break;case"duration":cr(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(If(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&cr(r,"ipv4",n.message,e),n.version!=="v4"&&cr(r,"ipv6",n.message,e);break}case"base64url":mt(r,ar.base64url,n.message,e);break;case"jwt":mt(r,ar.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,ar.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,ar.ipv6Cidr,n.message,e);break}case"emoji":mt(r,ar.emoji(),n.message,e);break;case"ulid":{mt(r,ar.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{cr(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,ar.base64,n.message,e);break}}break}case"nanoid":mt(r,ar.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function If(t,e){return e.patternStrategy==="escape"?$N(t):t}function $N(t){let e="";for(let r=0;r<t.length;r++)EN.has(t[r])||(e+="\\"),e+=t[r];return e}function cr(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):de(t,"format",e,r,n)}function mt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:PS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",PS(e,n),r,n)}function PS(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
60
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let p=this.seen.get(d),f=p.def??p.schema,m={...f};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,m))}p.isParent||this.override({zodSchema:d,jsonSchema:f,path:p.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,s.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var fb=b(()=>{});var dt=b(()=>{Fs();np();Jd();rb();Qa();up();wr();Xa();oc();Xp();cp();pb();db();mb();fb()});var Fm=b(()=>{dt()});function Um(t,e){let r={type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},...ce.normalizeParams(e)};return new QO(r)}var XO,QO,hb=b(()=>{dt();dt();Fm();XO=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");xe.init(t,e),t.def=e,t.parse=(r,n)=>Xd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Xn(t,r,n),t.parseAsync=async(r,n)=>ep(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Qn(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>At(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),QO=w("ZodMiniObject",(t,e)=>{nc.init(t,e),XO.init(t,e),ce.defineLazy(t,"shape",()=>e.shape)})});var gb=b(()=>{});var yb=b(()=>{});var _b=b(()=>{});var xb=b(()=>{dt();Fm();hb();gb();dt();oc();yb();_b()});var vb=b(()=>{xb()});var Hm=b(()=>{vb()});function qt(t){return!!t._zod}function rs(t){let e=Object.values(t);if(e.length===0)return Um({});let r=e.every(qt),n=e.every(s=>!qt(s));if(r)return Um(t);if(n)return jd(t);throw new Error("Mixed Zod versions detected in object shape.")}function cn(t,e){return qt(t)?Xn(t,e):t.safeParse(e)}async function mc(t,e){return qt(t)?await Qn(t,e):await t.safeParseAsync(e)}function un(t){if(!t)return;let e;if(qt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Bs(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return rs(t)}}if(qt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function fc(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 Sb(t){return t.description}function kb(t){if(qt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function hc(t){if(qt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var ri=b(()=>{Zo();Hm()});var Zm=b(()=>{dt()});var ni={};Le(ni,{ZodISODate:()=>Eb,ZodISODateTime:()=>wb,ZodISODuration:()=>Tb,ZodISOTime:()=>$b,date:()=>qm,datetime:()=>Bm,duration:()=>Wm,time:()=>Vm});function Bm(t){return ib(wb,t)}function qm(t){return ab(Eb,t)}function Vm(t){return cb($b,t)}function Wm(t){return ub(Tb,t)}var wb,Eb,$b,Tb,Gm=b(()=>{dt();Km();wb=w("ZodISODateTime",(t,e)=>{Yv.init(t,e),Ie.init(t,e)});Eb=w("ZodISODate",(t,e)=>{Xv.init(t,e),Ie.init(t,e)});$b=w("ZodISOTime",(t,e)=>{Qv.init(t,e),Ie.init(t,e)});Tb=w("ZodISODuration",(t,e)=>{eb.init(t,e),Ie.init(t,e)})});var Pb,Gq,si,Jm=b(()=>{dt();dt();Pb=(t,e)=>{Ja.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Kd(t,r)},flatten:{value:r=>Gd(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Gq=w("ZodError",Pb),si=w("ZodError",Pb,{Parent:Error})});var Rb,Cb,Ob,Ib,Ym=b(()=>{dt();Jm();Rb=Yd(si),Cb=Qd(si),Ob=tp(si),Ib=rp(si)});function S(t){return Qp(uI,t)}function ge(t){return bm(jb,t)}function Nb(t){return Sm(TI,t)}function Ge(t){return km(PI,t)}function zb(t){return wm(RI,t)}function Ae(){return Em(CI)}function II(t){return $m(OI,t)}function le(t,e){return lb(AI,t,e)}function z(t,e){let r={type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},...ce.normalizeParams(e)};return new Lb(r)}function pt(t,e){return new Lb({type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},catchall:Ae(),...ce.normalizeParams(e)})}function Te(t,e){return new Fb({type:"union",options:t,...ce.normalizeParams(e)})}function ef(t,e,r){return new NI({type:"union",options:e,discriminator:t,...ce.normalizeParams(r)})}function yc(t,e){return new DI({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new MI({type:"record",keyType:t,valueType:e,...ce.normalizeParams(r)})}function kt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Xm({type:"enum",entries:r,...ce.normalizeParams(e)})}function Z(t,e){return new jI({type:"literal",values:Array.isArray(t)?t:[t],...ce.normalizeParams(e)})}function Ub(t){return new zI({type:"transform",transform:t})}function Ne(t){return new Hb({type:"optional",innerType:t})}function Db(t){return new LI({type:"nullable",innerType:t})}function UI(t,e){return new FI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function ZI(t,e){return new HI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function BI(t,e){return new Zb({type:"nonoptional",innerType:t,...ce.normalizeParams(e)})}function VI(t,e){return new qI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Qm(t,e){return new WI({type:"pipe",in:t,out:e})}function KI(t){return new GI({type:"readonly",innerType:t})}function JI(t){let e=new Ye({check:"custom"});return e._zod.check=t,e}function qb(t,e){return jm(Bb,t??(()=>!0),e)}function YI(t,e={}){return zm(Bb,t,e)}function XI(t){let e=JI(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ce.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(ce.issue(s))}},t(r.value,r)));return e}function tf(t,e){return Qm(Ub(t),e)}var je,Mb,uI,Ie,lI,Ab,gc,dI,pI,mI,fI,hI,gI,yI,_I,xI,vI,bI,SI,kI,wI,EI,$I,jb,TI,PI,RI,CI,OI,AI,Lb,Fb,NI,DI,MI,Xm,jI,zI,Hb,LI,FI,HI,Zb,qI,WI,GI,Bb,Km=b(()=>{dt();dt();Zm();Gm();Ym();je=w("ZodType",(t,e)=>(xe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>At(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Rb(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ob(t,r,n),t.parseAsync=async(r,n)=>Cb(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ib(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(YI(r,n)),t.superRefine=r=>t.check(XI(r)),t.overwrite=r=>t.check(es(r)),t.optional=()=>Ne(t),t.nullable=()=>Db(t),t.nullish=()=>Ne(Db(t)),t.nonoptional=r=>BI(t,r),t.array=()=>le(t),t.or=r=>Te([t,r]),t.and=r=>yc(t,r),t.transform=r=>Qm(t,Ub(r)),t.default=r=>UI(t,r),t.prefault=r=>ZI(t,r),t.catch=r=>VI(t,r),t.pipe=r=>Qm(t,r),t.readonly=()=>KI(t),t.describe=r=>{let n=t.clone();return an.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return an.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return an.get(t);let n=t.clone();return an.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Mb=w("_ZodString",(t,e)=>{Xo.init(t,e),je.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Tm(...n)),t.includes=(...n)=>t.check(Cm(...n)),t.startsWith=(...n)=>t.check(Om(...n)),t.endsWith=(...n)=>t.check(Im(...n)),t.min=(...n)=>t.check(Zs(...n)),t.max=(...n)=>t.check(lc(...n)),t.length=(...n)=>t.check(dc(...n)),t.nonempty=(...n)=>t.check(Zs(1,...n)),t.lowercase=n=>t.check(Pm(n)),t.uppercase=n=>t.check(Rm(n)),t.trim=()=>t.check(Nm()),t.normalize=(...n)=>t.check(Am(...n)),t.toLowerCase=()=>t.check(Dm()),t.toUpperCase=()=>t.check(Mm())}),uI=w("ZodString",(t,e)=>{Xo.init(t,e),Mb.init(t,e),t.email=r=>t.check(em(lI,r)),t.url=r=>t.check(om(dI,r)),t.jwt=r=>t.check(vm($I,r)),t.emoji=r=>t.check(im(pI,r)),t.guid=r=>t.check(ic(Ab,r)),t.uuid=r=>t.check(tm(gc,r)),t.uuidv4=r=>t.check(rm(gc,r)),t.uuidv6=r=>t.check(nm(gc,r)),t.uuidv7=r=>t.check(sm(gc,r)),t.nanoid=r=>t.check(am(mI,r)),t.guid=r=>t.check(ic(Ab,r)),t.cuid=r=>t.check(cm(fI,r)),t.cuid2=r=>t.check(um(hI,r)),t.ulid=r=>t.check(lm(gI,r)),t.base64=r=>t.check(ym(kI,r)),t.base64url=r=>t.check(_m(wI,r)),t.xid=r=>t.check(dm(yI,r)),t.ksuid=r=>t.check(pm(_I,r)),t.ipv4=r=>t.check(mm(xI,r)),t.ipv6=r=>t.check(fm(vI,r)),t.cidrv4=r=>t.check(hm(bI,r)),t.cidrv6=r=>t.check(gm(SI,r)),t.e164=r=>t.check(xm(EI,r)),t.datetime=r=>t.check(Bm(r)),t.date=r=>t.check(qm(r)),t.time=r=>t.check(Vm(r)),t.duration=r=>t.check(Wm(r))});Ie=w("ZodStringFormat",(t,e)=>{we.init(t,e),Mb.init(t,e)}),lI=w("ZodEmail",(t,e)=>{mp.init(t,e),Ie.init(t,e)}),Ab=w("ZodGUID",(t,e)=>{dp.init(t,e),Ie.init(t,e)}),gc=w("ZodUUID",(t,e)=>{pp.init(t,e),Ie.init(t,e)}),dI=w("ZodURL",(t,e)=>{fp.init(t,e),Ie.init(t,e)}),pI=w("ZodEmoji",(t,e)=>{hp.init(t,e),Ie.init(t,e)}),mI=w("ZodNanoID",(t,e)=>{gp.init(t,e),Ie.init(t,e)}),fI=w("ZodCUID",(t,e)=>{yp.init(t,e),Ie.init(t,e)}),hI=w("ZodCUID2",(t,e)=>{_p.init(t,e),Ie.init(t,e)}),gI=w("ZodULID",(t,e)=>{xp.init(t,e),Ie.init(t,e)}),yI=w("ZodXID",(t,e)=>{vp.init(t,e),Ie.init(t,e)}),_I=w("ZodKSUID",(t,e)=>{bp.init(t,e),Ie.init(t,e)}),xI=w("ZodIPv4",(t,e)=>{Sp.init(t,e),Ie.init(t,e)}),vI=w("ZodIPv6",(t,e)=>{kp.init(t,e),Ie.init(t,e)}),bI=w("ZodCIDRv4",(t,e)=>{wp.init(t,e),Ie.init(t,e)}),SI=w("ZodCIDRv6",(t,e)=>{Ep.init(t,e),Ie.init(t,e)}),kI=w("ZodBase64",(t,e)=>{$p.init(t,e),Ie.init(t,e)}),wI=w("ZodBase64URL",(t,e)=>{Tp.init(t,e),Ie.init(t,e)}),EI=w("ZodE164",(t,e)=>{Pp.init(t,e),Ie.init(t,e)}),$I=w("ZodJWT",(t,e)=>{Rp.init(t,e),Ie.init(t,e)}),jb=w("ZodNumber",(t,e)=>{rc.init(t,e),je.init(t,e),t.gt=(n,s)=>t.check(cc(n,s)),t.gte=(n,s)=>t.check(ti(n,s)),t.min=(n,s)=>t.check(ti(n,s)),t.lt=(n,s)=>t.check(ac(n,s)),t.lte=(n,s)=>t.check(ei(n,s)),t.max=(n,s)=>t.check(ei(n,s)),t.int=n=>t.check(Nb(n)),t.safe=n=>t.check(Nb(n)),t.positive=n=>t.check(cc(0,n)),t.nonnegative=n=>t.check(ti(0,n)),t.negative=n=>t.check(ac(0,n)),t.nonpositive=n=>t.check(ei(0,n)),t.multipleOf=(n,s)=>t.check(uc(n,s)),t.step=(n,s)=>t.check(uc(n,s)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});TI=w("ZodNumberFormat",(t,e)=>{Cp.init(t,e),jb.init(t,e)});PI=w("ZodBoolean",(t,e)=>{Op.init(t,e),je.init(t,e)});RI=w("ZodNull",(t,e)=>{Ip.init(t,e),je.init(t,e)});CI=w("ZodUnknown",(t,e)=>{Ap.init(t,e),je.init(t,e)});OI=w("ZodNever",(t,e)=>{Np.init(t,e),je.init(t,e)});AI=w("ZodArray",(t,e)=>{Dp.init(t,e),je.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Zs(r,n)),t.nonempty=r=>t.check(Zs(1,r)),t.max=(r,n)=>t.check(lc(r,n)),t.length=(r,n)=>t.check(dc(r,n)),t.unwrap=()=>t.element});Lb=w("ZodObject",(t,e)=>{nc.init(t,e),je.init(t,e),ce.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>kt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ae()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ae()}),t.strict=()=>t.clone({...t._zod.def,catchall:II()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ce.extend(t,r),t.merge=r=>ce.merge(t,r),t.pick=r=>ce.pick(t,r),t.omit=r=>ce.omit(t,r),t.partial=(...r)=>ce.partial(Hb,t,r[0]),t.required=(...r)=>ce.required(Zb,t,r[0])});Fb=w("ZodUnion",(t,e)=>{sc.init(t,e),je.init(t,e),t.options=e.options});NI=w("ZodDiscriminatedUnion",(t,e)=>{Fb.init(t,e),Mp.init(t,e)});DI=w("ZodIntersection",(t,e)=>{jp.init(t,e),je.init(t,e)});MI=w("ZodRecord",(t,e)=>{zp.init(t,e),je.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Xm=w("ZodEnum",(t,e)=>{Lp.init(t,e),je.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Xm({...e,checks:[],...ce.normalizeParams(s),entries:o})},t.exclude=(n,s)=>{let o={...e.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Xm({...e,checks:[],...ce.normalizeParams(s),entries:o})}});jI=w("ZodLiteral",(t,e)=>{Fp.init(t,e),je.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]}})});zI=w("ZodTransform",(t,e)=>{Up.init(t,e),je.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ce.issue(o,r.value,e));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ce.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});Hb=w("ZodOptional",(t,e)=>{Hp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});LI=w("ZodNullable",(t,e)=>{Zp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});FI=w("ZodDefault",(t,e)=>{Bp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});HI=w("ZodPrefault",(t,e)=>{qp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});Zb=w("ZodNonOptional",(t,e)=>{Vp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});qI=w("ZodCatch",(t,e)=>{Wp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});WI=w("ZodPipe",(t,e)=>{Gp.init(t,e),je.init(t,e),t.in=e.in,t.out=e.out});GI=w("ZodReadonly",(t,e)=>{Kp.init(t,e),je.init(t,e)});Bb=w("ZodCustom",(t,e)=>{Jp.init(t,e),je.init(t,e)})});var Vb=b(()=>{});var Wb=b(()=>{});var Gb=b(()=>{dt();Km();Zm();Jm();Ym();Vb();dt();sb();oc();Gm();Wb();It(nb())});var Kb=b(()=>{Gb()});var Jb=b(()=>{Kb()});function mS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function fS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var nf,Yb,ln,xc,We,Xb,Qb,l4,tA,rA,sf,Nt,oi,eS,Xe,Vt,Wt,Qe,vc,tS,of,rS,nS,af,ii,V,cf,sS,oS,d4,bc,nA,Sc,sA,ai,qs,iS,oA,iA,aA,cA,uA,lA,uf,dA,pA,lf,kc,mA,fA,wc,hA,ci,ui,gA,li,Vs,yA,di,Ec,$c,Tc,p4,Pc,Rc,Cc,aS,cS,uS,df,lS,pi,Ws,dS,_A,Gs,xA,Ks,vA,pf,bA,Oc,SA,kA,wA,EA,$A,TA,PA,RA,CA,OA,Js,IA,AA,Ic,mf,ff,hf,NA,DA,MA,gf,jA,zA,LA,FA,UA,pS,Ac,HA,Nc,m4,ZA,Ys,BA,f4,mi,qA,yf,VA,WA,GA,KA,JA,YA,XA,_c,QA,eN,tN,fi,_f,rN,nN,sN,oN,iN,aN,cN,uN,lN,dN,pN,mN,fN,hN,gN,yN,_N,xN,Xs,vN,bN,SN,Dc,kN,wN,EN,xf,$N,h4,g4,y4,_4,x4,v4,H,rf,ns=b(()=>{Jb();nf="2025-11-25",Yb=[nf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ln="io.modelcontextprotocol/related-task",xc="2.0",We=qb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Xb=Te([S(),ge().int()]),Qb=S(),l4=pt({ttl:ge().optional(),pollInterval:ge().optional()}),tA=z({ttl:ge().optional()}),rA=z({taskId:S()}),sf=pt({progressToken:Xb.optional(),[ln]:rA.optional()}),Nt=z({_meta:sf.optional()}),oi=Nt.extend({task:tA.optional()}),eS=t=>oi.safeParse(t).success,Xe=z({method:S(),params:Nt.loose().optional()}),Vt=z({_meta:sf.optional()}),Wt=z({method:S(),params:Vt.loose().optional()}),Qe=pt({_meta:sf.optional()}),vc=Te([S(),ge().int()]),tS=z({jsonrpc:Z(xc),id:vc,...Xe.shape}).strict(),of=t=>tS.safeParse(t).success,rS=z({jsonrpc:Z(xc),...Wt.shape}).strict(),nS=t=>rS.safeParse(t).success,af=z({jsonrpc:Z(xc),id:vc,result:Qe}).strict(),ii=t=>af.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"})(V||(V={}));cf=z({jsonrpc:Z(xc),id:vc.optional(),error:z({code:ge().int(),message:S(),data:Ae().optional()})}).strict(),sS=t=>cf.safeParse(t).success,oS=Te([tS,rS,af,cf]),d4=Te([af,cf]),bc=Qe.strict(),nA=Vt.extend({requestId:vc.optional(),reason:S().optional()}),Sc=Wt.extend({method:Z("notifications/cancelled"),params:nA}),sA=z({src:S(),mimeType:S().optional(),sizes:le(S()).optional(),theme:kt(["light","dark"]).optional()}),ai=z({icons:le(sA).optional()}),qs=z({name:S(),title:S().optional()}),iS=qs.extend({...qs.shape,...ai.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),oA=yc(z({applyDefaults:Ge().optional()}),Ee(S(),Ae())),iA=tf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,yc(z({form:oA.optional(),url:We.optional()}),Ee(S(),Ae()).optional())),aA=pt({list:We.optional(),cancel:We.optional(),requests:pt({sampling:pt({createMessage:We.optional()}).optional(),elicitation:pt({create:We.optional()}).optional()}).optional()}),cA=pt({list:We.optional(),cancel:We.optional(),requests:pt({tools:pt({call:We.optional()}).optional()}).optional()}),uA=z({experimental:Ee(S(),We).optional(),sampling:z({context:We.optional(),tools:We.optional()}).optional(),elicitation:iA.optional(),roots:z({listChanged:Ge().optional()}).optional(),tasks:aA.optional(),extensions:Ee(S(),We).optional()}),lA=Nt.extend({protocolVersion:S(),capabilities:uA,clientInfo:iS}),uf=Xe.extend({method:Z("initialize"),params:lA}),dA=z({experimental:Ee(S(),We).optional(),logging:We.optional(),completions:We.optional(),prompts:z({listChanged:Ge().optional()}).optional(),resources:z({subscribe:Ge().optional(),listChanged:Ge().optional()}).optional(),tools:z({listChanged:Ge().optional()}).optional(),tasks:cA.optional(),extensions:Ee(S(),We).optional()}),pA=Qe.extend({protocolVersion:S(),capabilities:dA,serverInfo:iS,instructions:S().optional()}),lf=Wt.extend({method:Z("notifications/initialized"),params:Vt.optional()}),kc=Xe.extend({method:Z("ping"),params:Nt.optional()}),mA=z({progress:ge(),total:Ne(ge()),message:Ne(S())}),fA=z({...Vt.shape,...mA.shape,progressToken:Xb}),wc=Wt.extend({method:Z("notifications/progress"),params:fA}),hA=Nt.extend({cursor:Qb.optional()}),ci=Xe.extend({params:hA.optional()}),ui=Qe.extend({nextCursor:Qb.optional()}),gA=kt(["working","input_required","completed","failed","cancelled"]),li=z({taskId:S(),status:gA,ttl:Te([ge(),zb()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ne(ge()),statusMessage:Ne(S())}),Vs=Qe.extend({task:li}),yA=Vt.merge(li),di=Wt.extend({method:Z("notifications/tasks/status"),params:yA}),Ec=Xe.extend({method:Z("tasks/get"),params:Nt.extend({taskId:S()})}),$c=Qe.merge(li),Tc=Xe.extend({method:Z("tasks/result"),params:Nt.extend({taskId:S()})}),p4=Qe.loose(),Pc=ci.extend({method:Z("tasks/list")}),Rc=ui.extend({tasks:le(li)}),Cc=Xe.extend({method:Z("tasks/cancel"),params:Nt.extend({taskId:S()})}),aS=Qe.merge(li),cS=z({uri:S(),mimeType:Ne(S()),_meta:Ee(S(),Ae()).optional()}),uS=cS.extend({text:S()}),df=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),lS=cS.extend({blob:df}),pi=kt(["user","assistant"]),Ws=z({audience:le(pi).optional(),priority:ge().min(0).max(1).optional(),lastModified:ni.datetime({offset:!0}).optional()}),dS=z({...qs.shape,...ai.shape,uri:S(),description:Ne(S()),mimeType:Ne(S()),size:Ne(ge()),annotations:Ws.optional(),_meta:Ne(pt({}))}),_A=z({...qs.shape,...ai.shape,uriTemplate:S(),description:Ne(S()),mimeType:Ne(S()),annotations:Ws.optional(),_meta:Ne(pt({}))}),Gs=ci.extend({method:Z("resources/list")}),xA=ui.extend({resources:le(dS)}),Ks=ci.extend({method:Z("resources/templates/list")}),vA=ui.extend({resourceTemplates:le(_A)}),pf=Nt.extend({uri:S()}),bA=pf,Oc=Xe.extend({method:Z("resources/read"),params:bA}),SA=Qe.extend({contents:le(Te([uS,lS]))}),kA=Wt.extend({method:Z("notifications/resources/list_changed"),params:Vt.optional()}),wA=pf,EA=Xe.extend({method:Z("resources/subscribe"),params:wA}),$A=pf,TA=Xe.extend({method:Z("resources/unsubscribe"),params:$A}),PA=Vt.extend({uri:S()}),RA=Wt.extend({method:Z("notifications/resources/updated"),params:PA}),CA=z({name:S(),description:Ne(S()),required:Ne(Ge())}),OA=z({...qs.shape,...ai.shape,description:Ne(S()),arguments:Ne(le(CA)),_meta:Ne(pt({}))}),Js=ci.extend({method:Z("prompts/list")}),IA=ui.extend({prompts:le(OA)}),AA=Nt.extend({name:S(),arguments:Ee(S(),S()).optional()}),Ic=Xe.extend({method:Z("prompts/get"),params:AA}),mf=z({type:Z("text"),text:S(),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),ff=z({type:Z("image"),data:df,mimeType:S(),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),hf=z({type:Z("audio"),data:df,mimeType:S(),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),NA=z({type:Z("tool_use"),name:S(),id:S(),input:Ee(S(),Ae()),_meta:Ee(S(),Ae()).optional()}),DA=z({type:Z("resource"),resource:Te([uS,lS]),annotations:Ws.optional(),_meta:Ee(S(),Ae()).optional()}),MA=dS.extend({type:Z("resource_link")}),gf=Te([mf,ff,hf,MA,DA]),jA=z({role:pi,content:gf}),zA=Qe.extend({description:S().optional(),messages:le(jA)}),LA=Wt.extend({method:Z("notifications/prompts/list_changed"),params:Vt.optional()}),FA=z({title:S().optional(),readOnlyHint:Ge().optional(),destructiveHint:Ge().optional(),idempotentHint:Ge().optional(),openWorldHint:Ge().optional()}),UA=z({taskSupport:kt(["required","optional","forbidden"]).optional()}),pS=z({...qs.shape,...ai.shape,description:S().optional(),inputSchema:z({type:Z("object"),properties:Ee(S(),We).optional(),required:le(S()).optional()}).catchall(Ae()),outputSchema:z({type:Z("object"),properties:Ee(S(),We).optional(),required:le(S()).optional()}).catchall(Ae()).optional(),annotations:FA.optional(),execution:UA.optional(),_meta:Ee(S(),Ae()).optional()}),Ac=ci.extend({method:Z("tools/list")}),HA=ui.extend({tools:le(pS)}),Nc=Qe.extend({content:le(gf).default([]),structuredContent:Ee(S(),Ae()).optional(),isError:Ge().optional()}),m4=Nc.or(Qe.extend({toolResult:Ae()})),ZA=oi.extend({name:S(),arguments:Ee(S(),Ae()).optional()}),Ys=Xe.extend({method:Z("tools/call"),params:ZA}),BA=Wt.extend({method:Z("notifications/tools/list_changed"),params:Vt.optional()}),f4=z({autoRefresh:Ge().default(!0),debounceMs:ge().int().nonnegative().default(300)}),mi=kt(["debug","info","notice","warning","error","critical","alert","emergency"]),qA=Nt.extend({level:mi}),yf=Xe.extend({method:Z("logging/setLevel"),params:qA}),VA=Vt.extend({level:mi,logger:S().optional(),data:Ae()}),WA=Wt.extend({method:Z("notifications/message"),params:VA}),GA=z({name:S().optional()}),KA=z({hints:le(GA).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),JA=z({mode:kt(["auto","required","none"]).optional()}),YA=z({type:Z("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:le(gf).default([]),structuredContent:z({}).loose().optional(),isError:Ge().optional(),_meta:Ee(S(),Ae()).optional()}),XA=ef("type",[mf,ff,hf]),_c=ef("type",[mf,ff,hf,NA,YA]),QA=z({role:pi,content:Te([_c,le(_c)]),_meta:Ee(S(),Ae()).optional()}),eN=oi.extend({messages:le(QA),modelPreferences:KA.optional(),systemPrompt:S().optional(),includeContext:kt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:le(S()).optional(),metadata:We.optional(),tools:le(pS).optional(),toolChoice:JA.optional()}),tN=Xe.extend({method:Z("sampling/createMessage"),params:eN}),fi=Qe.extend({model:S(),stopReason:Ne(kt(["endTurn","stopSequence","maxTokens"]).or(S())),role:pi,content:XA}),_f=Qe.extend({model:S(),stopReason:Ne(kt(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:pi,content:Te([_c,le(_c)])}),rN=z({type:Z("boolean"),title:S().optional(),description:S().optional(),default:Ge().optional()}),nN=z({type:Z("string"),title:S().optional(),description:S().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:kt(["email","uri","date","date-time"]).optional(),default:S().optional()}),sN=z({type:kt(["number","integer"]),title:S().optional(),description:S().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),oN=z({type:Z("string"),title:S().optional(),description:S().optional(),enum:le(S()),default:S().optional()}),iN=z({type:Z("string"),title:S().optional(),description:S().optional(),oneOf:le(z({const:S(),title:S()})),default:S().optional()}),aN=z({type:Z("string"),title:S().optional(),description:S().optional(),enum:le(S()),enumNames:le(S()).optional(),default:S().optional()}),cN=Te([oN,iN]),uN=z({type:Z("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({type:Z("string"),enum:le(S())}),default:le(S()).optional()}),lN=z({type:Z("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({anyOf:le(z({const:S(),title:S()}))}),default:le(S()).optional()}),dN=Te([uN,lN]),pN=Te([aN,cN,dN]),mN=Te([pN,rN,nN,sN]),fN=oi.extend({mode:Z("form").optional(),message:S(),requestedSchema:z({type:Z("object"),properties:Ee(S(),mN),required:le(S()).optional()})}),hN=oi.extend({mode:Z("url"),message:S(),elicitationId:S(),url:S().url()}),gN=Te([fN,hN]),yN=Xe.extend({method:Z("elicitation/create"),params:gN}),_N=Vt.extend({elicitationId:S()}),xN=Wt.extend({method:Z("notifications/elicitation/complete"),params:_N}),Xs=Qe.extend({action:kt(["accept","decline","cancel"]),content:tf(t=>t===null?void 0:t,Ee(S(),Te([S(),ge(),Ge(),le(S())])).optional())}),vN=z({type:Z("ref/resource"),uri:S()}),bN=z({type:Z("ref/prompt"),name:S()}),SN=Nt.extend({ref:Te([bN,vN]),argument:z({name:S(),value:S()}),context:z({arguments:Ee(S(),S()).optional()}).optional()}),Dc=Xe.extend({method:Z("completion/complete"),params:SN});kN=Qe.extend({completion:pt({values:le(S()).max(100),total:Ne(ge().int()),hasMore:Ne(Ge())})}),wN=z({uri:S().startsWith("file://"),name:S().optional(),_meta:Ee(S(),Ae()).optional()}),EN=Xe.extend({method:Z("roots/list"),params:Nt.optional()}),xf=Qe.extend({roots:le(wN)}),$N=Wt.extend({method:Z("notifications/roots/list_changed"),params:Vt.optional()}),h4=Te([kc,uf,Dc,yf,Ic,Js,Gs,Ks,Oc,EA,TA,Ys,Ac,Ec,Tc,Pc,Cc]),g4=Te([Sc,wc,lf,$N,di]),y4=Te([bc,fi,_f,Xs,xf,$c,Rc,Vs]),_4=Te([kc,tN,yN,EN,Ec,Tc,Pc,Cc]),x4=Te([Sc,wc,WA,RA,kA,BA,LA,di,xN]),v4=Te([bc,pA,kN,zA,IA,xA,vA,SA,Nc,HA,$c,Rc,Vs]),H=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===V.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new rf(s.elicitations,r)}return new t(e,r,n)}},rf=class extends H{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(V.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function dn(t){return t==="completed"||t==="failed"||t==="cancelled"}var hS=b(()=>{});var yS,gS,_S,Mc=b(()=>{yS=Symbol("Let zodToJsonSchema decide on which parser to use"),gS={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"},_S=t=>typeof t=="string"?{...gS,name:t}:{...gS,...t}});var xS,vf=b(()=>{Mc();xS=t=>{let e=_S(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function bf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,s){t[e]=r,bf(t,e,n,s)}var pn=b(()=>{});var jc,zc=b(()=>{jc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function De(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?jc(e,t.currentPath):e.join("/")}}var Gt=b(()=>{zc()});function vS(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==I.ZodAny&&(r.items=J(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Sf=b(()=>{Zo();pn();Be()});function bS(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var kf=b(()=>{pn()});function SS(){return{type:"boolean"}}var wf=b(()=>{});function Lc(t,e){return J(t.type._def,e)}var Fc=b(()=>{Be()});var kS,Ef=b(()=>{Be();kS=(t,e)=>J(t.innerType._def,e)});function $f(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>$f(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return TN(t,e)}}var TN,Tf=b(()=>{pn();TN=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function wS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var Pf=b(()=>{Be()});function ES(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):De(e)}var Rf=b(()=>{Be();Gt()});function $S(t){return{type:"string",enum:Array.from(t.values)}}var Cf=b(()=>{});function TS(t,e){let r=[J(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(PN(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var PN,Of=b(()=>{Be();PN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function PS(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var If=b(()=>{});function Uc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":cr(r,"email",n.message,e);break;case"format:idn-email":cr(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,ar.email,n.message,e);break}break;case"url":cr(r,"uri",n.message,e);break;case"uuid":cr(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,ar.cuid,n.message,e);break;case"cuid2":mt(r,ar.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${Nf(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${Nf(n.value,e)}$`),n.message,e);break;case"datetime":cr(r,"date-time",n.message,e);break;case"date":cr(r,"date",n.message,e);break;case"time":cr(r,"time",n.message,e);break;case"duration":cr(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(Nf(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&cr(r,"ipv4",n.message,e),n.version!=="v4"&&cr(r,"ipv6",n.message,e);break}case"base64url":mt(r,ar.base64url,n.message,e);break;case"jwt":mt(r,ar.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,ar.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,ar.ipv6Cidr,n.message,e);break}case"emoji":mt(r,ar.emoji(),n.message,e);break;case"ulid":{mt(r,ar.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{cr(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,ar.base64,n.message,e);break}}break}case"nanoid":mt(r,ar.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Nf(t,e){return e.patternStrategy==="escape"?CN(t):t}function CN(t){let e="";for(let r=0;r<t.length;r++)RN.has(t[r])||(e+="\\"),e+=t[r];return e}function cr(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):de(t,"format",e,r,n)}function mt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:RS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",RS(e,n),r,n)}function RS(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
61
61
  ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
62
62
  ]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
63
63
  `:`[${n[c]}\r
64
- ]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}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 s}var Of,ar,EN,Uc=b(()=>{pn();ar={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:()=>(Of===void 0&&(Of=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Of),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-_]*$/};EN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Hc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===I.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===I.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Fc(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===I.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===I.ZodBranded&&t.keyType._def.type._def.typeName===I.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=zc(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Zc=b(()=>{Ho();Be();Uc();Lc();Gt()});function RS(t,e){if(e.mapStrategy==="record")return Hc(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Af=b(()=>{Be();Zc();Gt()});function CS(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var Nf=b(()=>{});function OS(t){return t.target==="openAi"?void 0:{not:De({...t,currentPath:[...t.currentPath,"not"]})}}var Df=b(()=>{Gt()});function IS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Mf=b(()=>{});function NS(t,e){if(e.target==="openApi3")return AS(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in fi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=fi[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return AS(t,e)}var fi,AS,Bc=b(()=>{Be();fi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};AS=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>J(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function DS(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:fi[t.innerType._def.typeName],nullable:!0}:{type:[fi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=J(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var jf=b(()=>{Be();Bc()});function MS(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",xf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var zf=b(()=>{pn()});function jS(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=PN(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=J(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||s.push(a))}s.length&&(n.required=s);let i=TN(t,e);return i!==void 0&&(n.additionalProperties=i),n}function TN(t,e){if(t.catchall._def.typeName!=="ZodNever")return J(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 PN(t){try{return t.isOptional()}catch{return!0}}var Lf=b(()=>{Be()});var zS,Ff=b(()=>{Be();Gt();zS=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return J(t.innerType._def,e);let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:De(e)},r]}:De(e)}});var LS,Uf=b(()=>{Be();LS=(t,e)=>{if(e.pipeStrategy==="input")return J(t.in._def,e);if(e.pipeStrategy==="output")return J(t.out._def,e);let r=J(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=J(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function FS(t,e){return J(t.type._def,e)}var Hf=b(()=>{Be()});function US(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Zf=b(()=>{pn();Be()});function HS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:J(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Bf=b(()=>{Be()});function ZS(t){return{not:De(t)}}var qf=b(()=>{Gt()});function BS(t){return De(t)}var Vf=b(()=>{Gt()});var qS,Wf=b(()=>{Be();qS=(t,e)=>J(t.innerType._def,e)});var VS,Gf=b(()=>{Ho();Gt();vf();bf();Sf();Lc();kf();Ef();$f();Tf();Pf();Rf();Cf();Af();Nf();Df();Mf();jf();zf();Lf();Ff();Uf();Hf();Zc();Zf();Uc();Bf();qf();Bc();Vf();Wf();VS=(t,e,r)=>{switch(e){case I.ZodString:return Fc(t,r);case I.ZodNumber:return MS(t,r);case I.ZodObject:return jS(t,r);case I.ZodBigInt:return vS(t,r);case I.ZodBoolean:return bS();case I.ZodDate:return wf(t,r);case I.ZodUndefined:return ZS(r);case I.ZodNull:return IS(r);case I.ZodArray:return xS(t,r);case I.ZodUnion:case I.ZodDiscriminatedUnion:return NS(t,r);case I.ZodIntersection:return $S(t,r);case I.ZodTuple:return HS(t,r);case I.ZodRecord:return Hc(t,r);case I.ZodLiteral:return TS(t,r);case I.ZodEnum:return ES(t);case I.ZodNativeEnum:return CS(t);case I.ZodNullable:return DS(t,r);case I.ZodOptional:return zS(t,r);case I.ZodMap:return RS(t,r);case I.ZodSet:return US(t,r);case I.ZodLazy:return()=>t.getter()._def;case I.ZodPromise:return FS(t,r);case I.ZodNaN:case I.ZodNever:return OS(r);case I.ZodEffects:return wS(t,r);case I.ZodAny:return De(r);case I.ZodUnknown:return BS(r);case I.ZodDefault:return kS(t,r);case I.ZodBranded:return zc(t,r);case I.ZodReadonly:return qS(t,r);case I.ZodCatch:return SS(t,r);case I.ZodPipeline:return LS(t,r);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(n=>{})(e)}}});function J(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==gS)return a}if(n&&!r){let a=RN(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=VS(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&CN(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var RN,CN,Be=b(()=>{Dc();Gf();jc();Gt();RN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Mc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},CN=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var WS=b(()=>{});var Kf,Jf=b(()=>{Be();_f();Gt();Kf=(t,e)=>{let r=_S(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:J(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??De(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=J(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??De(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var GS=b(()=>{Dc();_f();pn();jc();Be();WS();Gt();vf();bf();Sf();Lc();kf();Ef();$f();Tf();Pf();Rf();Cf();Af();Nf();Df();Mf();jf();zf();Lf();Ff();Uf();Hf();Wf();Zc();Zf();Uc();Bf();qf();Bc();Vf();Gf();Jf();Jf()});function ON(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Yf(t,e){return qt(t)?jm(t,{target:ON(e?.target),io:e?.pipeStrategy??"input"}):Kf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Xf(t){let r=un(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Qf(t,e){let r=cn(t,e);if(!r.success)throw r.error;return r.data}var eh=b(()=>{Fm();ti();GS()});function KS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function JS(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];KS(i)&&KS(o)?r[s]={...i,...o}:r[s]=o}return r}var IN,qc,YS=b(()=>{ti();rs();fS();eh();IN=6e4,qc=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(bc,r=>{this._oncancel(r)}),this.setNotificationHandler(kc,r=>{this._onprogress(r)}),this.setRequestHandler(Sc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wc,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(V.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler($c,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,p=new H(l.error.code,l.error.message,l.error.data);d(p)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new H(V.InvalidParams,`Task not found: ${o}`);if(!dn(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(dn(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[ln]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Tc,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new H(V.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Rc,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(V.InvalidParams,`Task not found: ${r.params.taskId}`);if(dn(s.status))throw new H(V.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(V.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof H?s:new H(V.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),H.fromError(V.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),oi(o)||nS(o)?this._onresponse(o):nf(o)?this._onrequest(o,i):rS(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=H.fromError(V.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[ln]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:V.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):s?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Qb(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};o&&(l.relatedTask={taskId:o}),await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new H(V.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let m=f.relatedTask?.taskId??o;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:V.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),oi(e))n(e);else{let i=new H(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(oi(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),oi(e))s(e);else{let i=H.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof H?i:new H(V.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Vs,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new H(V.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},dn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new H(V.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new H(V.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof H?i:new H(V.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=v=>{d(v)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){l(v);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.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||{},[ln]:c}});let m=v=>{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(v)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof H?v:new H(V.RequestTimeout,String(v));d(y)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return d(v);try{let y=cn(r,v.result);y.success?u(y.data):d(y.error)}catch(y){d(y)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??IN,g=()=>m(H.fromError(V.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(p);x?x(y):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(p),d(y)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),d(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ec,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Pc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},iS,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ln]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ln]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ln]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Xf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Qf(e,s);return Promise.resolve(r(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Xf(e);this._notificationHandlers.set(n,s=>{let o=Qf(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&nf(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new H(V.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new H(V.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new H(V.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new H(V.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=li.parse({method:"notifications/tasks/status",params:a});await this.notification(c),dn(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new H(V.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(dn(a.status))throw new H(V.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let u=li.parse({method:"notifications/tasks/status",params:c});await this.notification(u),dn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var yi=D(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 hi=class{};he._CodeOrName=hi;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ns=class extends hi{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=ns;var Kt=class extends hi{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof ns&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Kt;he.nil=new Kt("");function XS(t,...e){let r=[t[0]],n=0;for(;n<e.length;)rh(r,e[n]),r.push(t[++n]);return new Kt(r)}he._=XS;var th=new Kt("+");function QS(t,...e){let r=[gi(t[0])],n=0;for(;n<e.length;)r.push(th),rh(r,e[n]),r.push(th,gi(t[++n]));return AN(r),new Kt(r)}he.str=QS;function rh(t,e){e instanceof Kt?t.push(...e._items):e instanceof ns?t.push(e):t.push(MN(e))}he.addCodeArg=rh;function AN(t){let e=1;for(;e<t.length-1;){if(t[e]===th){let r=NN(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function NN(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ns||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof ns))return`"${t}${e.slice(1)}`}function DN(t,e){return e.emptyStr()?t:t.emptyStr()?e:QS`${t}${e}`}he.strConcat=DN;function MN(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:gi(Array.isArray(t)?t.join(","):t)}function jN(t){return new Kt(gi(t))}he.stringify=jN;function gi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=gi;function zN(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Kt(`.${t}`):XS`[${t}]`}he.getProperty=zN;function LN(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Kt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=LN;function FN(t){return new Kt(t.toString())}he.regexpCode=FN});var oh=D(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var wt=yi(),nh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Vc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Vc||(Et.UsedValueState=Vc={}));Et.varKinds={const:new wt.Name("const"),let:new wt.Name("let"),var:new wt.Name("var")};var Wc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof wt.Name?e:this.name(e)}name(e){return new wt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Et.Scope=Wc;var Gc=class extends wt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,wt._)`.${new wt.Name(r)}[${n}]`}};Et.ValueScopeName=Gc;var UN=(0,wt._)`\n`,sh=class extends Wc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?UN:wt.nil}}get(){return this._scope}name(e){return new Gc(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(i);if(d)return d}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,wt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=wt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Vc.Started);let d=r(u);if(d){let l=this.opts.es5?Et.varKinds.var:Et.varKinds.const;o=(0,wt._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,wt._)`${o}${d}${this.opts._n}`;else throw new nh(u);c.set(u,Vc.Completed)})}return o}};Et.ValueScope=sh});var re=D(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var pe=yi(),ur=oh(),mn=yi();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return mn._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return mn.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return mn.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return mn.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return mn.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return mn.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return mn.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return mn.Name}});var Xc=oh();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Xc.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Xc.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Xc.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Xc.varKinds}});ne.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var jr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ih=class extends jr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ur.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=eo(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},Kc=class extends jr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=eo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return Yc(e,this.rhs)}},ah=class extends Kc{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ch=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},uh=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},lh=class extends jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},dh=class extends jr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=eo(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},_i=class extends jr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(HN(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>is(e,r.names),{})}},zr=class extends _i{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},ph=class extends _i{},Qs=class extends zr{};Qs.kind="else";var ss=class t extends zr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Qs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(ek(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=eo(this.condition,e,r),this}get names(){let e=super.names;return Yc(e,this.condition),this.else&&is(e,this.else.names),e}};ss.kind="if";var os=class extends zr{};os.kind="for";var mh=class extends os{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=eo(this.iteration,e,r),this}get names(){return is(super.names,this.iteration.names)}},fh=class extends os{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ur.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Yc(super.names,this.from);return Yc(e,this.to)}},Jc=class extends os{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=eo(this.iterable,e,r),this}get names(){return is(super.names,this.iterable.names)}},xi=class extends zr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};xi.kind="func";var vi=class extends _i{render(e){return"return "+super.render(e)}};vi.kind="return";var hh=class extends zr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&is(e,this.catch.names),this.finally&&is(e,this.finally.names),e}},bi=class extends zr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};bi.kind="catch";var Si=class extends zr{render(e){return"finally"+super.render(e)}};Si.kind="finally";var gh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
65
- `:""},this._extScope=e,this._scope=new ur.Scope({parent:e}),this._nodes=[new ph]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new ih(e,o,n)),o}const(e,r,n){return this._def(ur.varKinds.const,e,r,n)}let(e,r,n){return this._def(ur.varKinds.let,e,r,n)}var(e,r,n){return this._def(ur.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Kc(e,r,n))}add(e,r){return this._leafNode(new ah(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new dh(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,pe.addCodeArg)(r,s));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new ss(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new ss(e))}else(){return this._elseNode(new Qs)}endIf(){return this._endBlockNode(ss,Qs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new mh(e),r)}forRange(e,r,n,s,o=this.opts.es5?ur.varKinds.var:ur.varKinds.let){let i=this._scope.toName(e);return this._for(new fh(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ur.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(o,(0,pe._)`${i}[${a}]`),n(o)})}return this._for(new Jc("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ur.varKinds.var:ur.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Jc("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(os)}label(e){return this._leafNode(new ch(e))}break(e){return this._leafNode(new uh(e))}return(e){let r=new vi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(vi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new hh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new bi(o),r(o)}return n&&(this._currNode=s.finally=new Si,this.code(n)),this._endBlockNode(bi,Si)}throw(e){return this._leafNode(new lh(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=pe.nil,n,s){return this._blockNode(new xi(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(xi)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof ss))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};ne.CodeGen=gh;function is(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Yc(t,e){return e instanceof pe._CodeOrName?is(t,e.names):t}function eo(t,e,r){if(t instanceof pe.Name)return n(t);if(!s(t))return t;return new pe._Code(t._items.reduce((o,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof pe._Code&&o._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function HN(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function ek(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${yh(t)}`}ne.not=ek;var ZN=tk(ne.operators.AND);function BN(...t){return t.reduce(ZN)}ne.and=BN;var qN=tk(ne.operators.OR);function VN(...t){return t.reduce(qN)}ne.or=VN;function tk(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${yh(e)} ${t} ${yh(r)}`}function yh(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=D(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var be=re(),WN=yi();function GN(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=GN;function KN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(sk(t,e),!ok(e,t.self.RULES.all))}se.alwaysValidSchema=KN;function sk(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||ck(t,`unknown keyword: "${o}"`)}se.checkUnknownRules=sk;function ok(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=ok;function JN(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}se.schemaHasRulesButRef=JN;function YN({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,be._)`${r}`}return(0,be._)`${t}${e}${(0,be.getProperty)(n)}`}se.schemaRefOrVal=YN;function XN(t){return ik(decodeURIComponent(t))}se.unescapeFragment=XN;function QN(t){return encodeURIComponent(xh(t))}se.escapeFragment=QN;function xh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=xh;function ik(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=ik;function e1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=e1;function rk({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof be.Name?(o instanceof be.Name?t(s,o,i):e(s,o,i),i):o instanceof be.Name?(e(s,i,o),o):r(o,i);return a===be.Name&&!(c instanceof be.Name)?n(s,c):c}}se.mergeEvaluated={props:rk({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,be._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,be._)`${r} || {}`).code((0,be._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,be._)`${r} || {}`),vh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ak}),items:rk({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,be._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,be._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ak(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,be._)`{}`);return e!==void 0&&vh(t,r,e),r}se.evaluatedPropsToName=ak;function vh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,be._)`${e}${(0,be.getProperty)(n)}`,!0))}se.setEvaluated=vh;var nk={};function t1(t,e){return t.scopeValue("func",{ref:e,code:nk[e.code]||(nk[e.code]=new WN._Code(e.code))})}se.useFunc=t1;var _h;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_h||(se.Type=_h={}));function r1(t,e,r){if(t instanceof be.Name){let n=e===_h.Num;return r?n?(0,be._)`"[" + ${t} + "]"`:(0,be._)`"['" + ${t} + "']"`:n?(0,be._)`"/" + ${t}`:(0,be._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,be.getProperty)(t).toString():"/"+xh(t)}se.getErrorPath=r1;function ck(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}se.checkStrictMode=ck});var Lr=D(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var ot=re(),n1={data:new ot.Name("data"),valCxt:new ot.Name("valCxt"),instancePath:new ot.Name("instancePath"),parentData:new ot.Name("parentData"),parentDataProperty:new ot.Name("parentDataProperty"),rootData:new ot.Name("rootData"),dynamicAnchors:new ot.Name("dynamicAnchors"),vErrors:new ot.Name("vErrors"),errors:new ot.Name("errors"),this:new ot.Name("this"),self:new ot.Name("self"),scope:new ot.Name("scope"),json:new ot.Name("json"),jsonPos:new ot.Name("jsonPos"),jsonLen:new ot.Name("jsonLen"),jsonPart:new ot.Name("jsonPart")};bh.default=n1});var ki=D(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.extendErrors=it.resetErrorsCount=it.reportExtraError=it.reportError=it.keyword$DataError=it.keywordError=void 0;var fe=re(),Qc=me(),ft=Lr();it.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};it.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 s1(t,e=it.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=dk(t,e,r);n??(i||a)?uk(o,c):lk(s,(0,fe._)`[${c}]`)}it.reportError=s1;function o1(t,e=it.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=dk(t,e,r);uk(s,a),o||i||lk(n,ft.default.vErrors)}it.reportExtraError=o1;function i1(t,e){t.assign(ft.default.errors,e),t.if((0,fe._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}it.resetErrorsCount=i1;function a1({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,ft.default.errors,a=>{t.const(i,(0,fe._)`${ft.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(ft.default.instancePath,o.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}it.extendErrors=a1;function uk(t,e){let r=t.const("err",e);t.if((0,fe._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${ft.default.vErrors}.push(${r})`),t.code((0,fe._)`${ft.default.errors}++`)}function lk(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var as={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 dk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:c1(t,e,r)}function c1(t,e,r={}){let{gen:n,it:s}=t,o=[u1(s,r),l1(t,r)];return d1(t,e,o),n.object(...o)}function u1({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,Qc.getErrorPath)(e,Qc.Type.Str)}`:t;return[ft.default.instancePath,(0,fe.strConcat)(ft.default.instancePath,r)]}function l1({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,fe.str)`${e}/${t}`;return r&&(s=(0,fe.str)`${s}${(0,Qc.getErrorPath)(r,Qc.Type.Str)}`),[as.schemaPath,s]}function d1(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([as.keyword,s],[as.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([as.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([as.schema,i],[as.parentSchema,(0,fe._)`${d}${l}`],[ft.default.data,o]),u&&n.push([as.propertyName,u])}});var mk=D(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.boolOrEmptySchema=to.topBoolOrEmptySchema=void 0;var p1=ki(),m1=re(),f1=Lr(),h1={message:"boolean schema is false"};function g1(t){let{gen:e,schema:r,validateName:n}=t;r===!1?pk(t,!1):typeof r=="object"&&r.$async===!0?e.return(f1.default.data):(e.assign((0,m1._)`${n}.errors`,null),e.return(!0))}to.topBoolOrEmptySchema=g1;function y1(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),pk(t)):r.var(e,!0)}to.boolOrEmptySchema=y1;function pk(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,p1.reportError)(s,h1,void 0,e)}});var Sh=D(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.getRules=ro.isJSONType=void 0;var _1=["string","number","integer","boolean","null","object","array"],x1=new Set(_1);function v1(t){return typeof t=="string"&&x1.has(t)}ro.isJSONType=v1;function b1(){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:{}}}ro.getRules=b1});var kh=D(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.shouldUseRule=fn.shouldUseGroup=fn.schemaHasRulesForType=void 0;function S1({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&fk(t,n)}fn.schemaHasRulesForType=S1;function fk(t,e){return e.rules.some(r=>hk(t,r))}fn.shouldUseGroup=fk;function hk(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}fn.shouldUseRule=hk});var wi=D(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.reportTypeError=at.checkDataTypes=at.checkDataType=at.coerceAndCheckDataType=at.getJSONTypes=at.getSchemaTypes=at.DataType=void 0;var k1=Sh(),w1=kh(),E1=ki(),ee=re(),gk=me(),no;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(no||(at.DataType=no={}));function $1(t){let e=yk(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}at.getSchemaTypes=$1;function yk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(k1.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}at.getJSONTypes=yk;function T1(t,e){let{gen:r,data:n,opts:s}=t,o=P1(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,w1.schemaHasRulesForType)(t,e[0]));if(i){let a=Eh(e,n,s.strictNumbers,no.Wrong);r.if(a,()=>{o.length?R1(t,e,o):$h(t)})}return i}at.coerceAndCheckDataType=T1;var _k=new Set(["string","number","integer","boolean","null"]);function P1(t,e){return e?t.filter(r=>_k.has(r)||e==="array"&&r==="array"):[]}function R1(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,ee._)`typeof ${s}`),a=n.let("coerced",(0,ee._)`undefined`);o.coerceTypes==="array"&&n.if((0,ee._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,ee._)`${s}[0]`).assign(i,(0,ee._)`typeof ${s}`).if(Eh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(_k.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),$h(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(s,a),C1(t,a)});function c(u){switch(u){case"string":n.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${s}`).elseIf((0,ee._)`${s} === null`).assign(a,(0,ee._)`""`);return;case"number":n.elseIf((0,ee._)`${i} == "boolean" || ${s} === null
64
+ ]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}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 s}var Af,ar,RN,Hc=b(()=>{pn();ar={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:()=>(Af===void 0&&(Af=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Af),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-_]*$/};RN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Zc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===I.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===I.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Uc(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===I.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===I.ZodBranded&&t.keyType._def.type._def.typeName===I.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Lc(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Bc=b(()=>{Zo();Be();Hc();Fc();Gt()});function CS(t,e){if(e.mapStrategy==="record")return Zc(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Df=b(()=>{Be();Bc();Gt()});function OS(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var Mf=b(()=>{});function IS(t){return t.target==="openAi"?void 0:{not:De({...t,currentPath:[...t.currentPath,"not"]})}}var jf=b(()=>{Gt()});function AS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zf=b(()=>{});function DS(t,e){if(e.target==="openApi3")return NS(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in hi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=hi[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return NS(t,e)}var hi,NS,qc=b(()=>{Be();hi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};NS=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>J(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function MS(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:hi[t.innerType._def.typeName],nullable:!0}:{type:[hi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=J(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Lf=b(()=>{Be();qc()});function jS(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",bf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var Ff=b(()=>{pn()});function zS(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=IN(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=J(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||s.push(a))}s.length&&(n.required=s);let i=ON(t,e);return i!==void 0&&(n.additionalProperties=i),n}function ON(t,e){if(t.catchall._def.typeName!=="ZodNever")return J(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 IN(t){try{return t.isOptional()}catch{return!0}}var Uf=b(()=>{Be()});var LS,Hf=b(()=>{Be();Gt();LS=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return J(t.innerType._def,e);let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:De(e)},r]}:De(e)}});var FS,Zf=b(()=>{Be();FS=(t,e)=>{if(e.pipeStrategy==="input")return J(t.in._def,e);if(e.pipeStrategy==="output")return J(t.out._def,e);let r=J(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=J(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function US(t,e){return J(t.type._def,e)}var Bf=b(()=>{Be()});function HS(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var qf=b(()=>{pn();Be()});function ZS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:J(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Vf=b(()=>{Be()});function BS(t){return{not:De(t)}}var Wf=b(()=>{Gt()});function qS(t){return De(t)}var Gf=b(()=>{Gt()});var VS,Kf=b(()=>{Be();VS=(t,e)=>J(t.innerType._def,e)});var WS,Jf=b(()=>{Zo();Gt();Sf();kf();wf();Fc();Ef();Tf();Pf();Rf();Cf();Of();If();Df();Mf();jf();zf();Lf();Ff();Uf();Hf();Zf();Bf();Bc();qf();Hc();Vf();Wf();qc();Gf();Kf();WS=(t,e,r)=>{switch(e){case I.ZodString:return Uc(t,r);case I.ZodNumber:return jS(t,r);case I.ZodObject:return zS(t,r);case I.ZodBigInt:return bS(t,r);case I.ZodBoolean:return SS();case I.ZodDate:return $f(t,r);case I.ZodUndefined:return BS(r);case I.ZodNull:return AS(r);case I.ZodArray:return vS(t,r);case I.ZodUnion:case I.ZodDiscriminatedUnion:return DS(t,r);case I.ZodIntersection:return TS(t,r);case I.ZodTuple:return ZS(t,r);case I.ZodRecord:return Zc(t,r);case I.ZodLiteral:return PS(t,r);case I.ZodEnum:return $S(t);case I.ZodNativeEnum:return OS(t);case I.ZodNullable:return MS(t,r);case I.ZodOptional:return LS(t,r);case I.ZodMap:return CS(t,r);case I.ZodSet:return HS(t,r);case I.ZodLazy:return()=>t.getter()._def;case I.ZodPromise:return US(t,r);case I.ZodNaN:case I.ZodNever:return IS(r);case I.ZodEffects:return ES(t,r);case I.ZodAny:return De(r);case I.ZodUnknown:return qS(r);case I.ZodDefault:return wS(t,r);case I.ZodBranded:return Lc(t,r);case I.ZodReadonly:return VS(t,r);case I.ZodCatch:return kS(t,r);case I.ZodPipeline:return FS(t,r);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(n=>{})(e)}}});function J(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==yS)return a}if(n&&!r){let a=AN(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=WS(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&NN(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var AN,NN,Be=b(()=>{Mc();Jf();zc();Gt();AN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:jc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},NN=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var GS=b(()=>{});var Yf,Xf=b(()=>{Be();vf();Gt();Yf=(t,e)=>{let r=xS(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:J(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??De(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=J(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??De(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var KS=b(()=>{Mc();vf();pn();zc();Be();GS();Gt();Sf();kf();wf();Fc();Ef();Tf();Pf();Rf();Cf();Of();If();Df();Mf();jf();zf();Lf();Ff();Uf();Hf();Zf();Bf();Kf();Bc();qf();Hc();Vf();Wf();qc();Gf();Jf();Xf();Xf()});function DN(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Qf(t,e){return qt(t)?Lm(t,{target:DN(e?.target),io:e?.pipeStrategy??"input"}):Yf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function eh(t){let r=un(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=hc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function th(t,e){let r=cn(t,e);if(!r.success)throw r.error;return r.data}var rh=b(()=>{Hm();ri();KS()});function JS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function YS(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];JS(i)&&JS(o)?r[s]={...i,...o}:r[s]=o}return r}var MN,Vc,XS=b(()=>{ri();ns();hS();rh();MN=6e4,Vc=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(Sc,r=>{this._oncancel(r)}),this.setNotificationHandler(wc,r=>{this._onprogress(r)}),this.setRequestHandler(kc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ec,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(V.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Tc,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,p=new H(l.error.code,l.error.message,l.error.data);d(p)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new H(V.InvalidParams,`Task not found: ${o}`);if(!dn(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(dn(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[ln]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Pc,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new H(V.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Cc,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(V.InvalidParams,`Task not found: ${r.params.taskId}`);if(dn(s.status))throw new H(V.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(V.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof H?s:new H(V.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),H.fromError(V.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),ii(o)||sS(o)?this._onresponse(o):of(o)?this._onrequest(o,i):nS(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=H.fromError(V.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[ln]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:V.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):s?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=eS(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};o&&(l.relatedTask={taskId:o}),await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new H(V.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let m=f.relatedTask?.taskId??o;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:V.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ii(e))n(e);else{let i=new H(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(ii(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),ii(e))s(e);else{let i=H.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof H?i:new H(V.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Vs,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new H(V.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},dn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new H(V.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new H(V.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof H?i:new H(V.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=v=>{d(v)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){l(v);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.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||{},[ln]:c}});let m=v=>{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(v)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof H?v:new H(V.RequestTimeout,String(v));d(y)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return d(v);try{let y=cn(r,v.result);y.success?u(y.data):d(y.error)}catch(y){d(y)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??MN,g=()=>m(H.fromError(V.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(p);x?x(y):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(p),d(y)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),d(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},$c,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Rc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},aS,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ln]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ln]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ln]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=eh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=th(e,s);return Promise.resolve(r(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=eh(e);this._notificationHandlers.set(n,s=>{let o=th(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&of(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new H(V.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new H(V.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new H(V.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new H(V.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=di.parse({method:"notifications/tasks/status",params:a});await this.notification(c),dn(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new H(V.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(dn(a.status))throw new H(V.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let u=di.parse({method:"notifications/tasks/status",params:c});await this.notification(u),dn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var _i=D(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 gi=class{};he._CodeOrName=gi;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ss=class extends gi{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=ss;var Kt=class extends gi{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof ss&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Kt;he.nil=new Kt("");function QS(t,...e){let r=[t[0]],n=0;for(;n<e.length;)sh(r,e[n]),r.push(t[++n]);return new Kt(r)}he._=QS;var nh=new Kt("+");function ek(t,...e){let r=[yi(t[0])],n=0;for(;n<e.length;)r.push(nh),sh(r,e[n]),r.push(nh,yi(t[++n]));return jN(r),new Kt(r)}he.str=ek;function sh(t,e){e instanceof Kt?t.push(...e._items):e instanceof ss?t.push(e):t.push(FN(e))}he.addCodeArg=sh;function jN(t){let e=1;for(;e<t.length-1;){if(t[e]===nh){let r=zN(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function zN(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ss||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof ss))return`"${t}${e.slice(1)}`}function LN(t,e){return e.emptyStr()?t:t.emptyStr()?e:ek`${t}${e}`}he.strConcat=LN;function FN(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:yi(Array.isArray(t)?t.join(","):t)}function UN(t){return new Kt(yi(t))}he.stringify=UN;function yi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=yi;function HN(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Kt(`.${t}`):QS`[${t}]`}he.getProperty=HN;function ZN(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Kt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=ZN;function BN(t){return new Kt(t.toString())}he.regexpCode=BN});var ah=D(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var wt=_i(),oh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Wc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Wc||(Et.UsedValueState=Wc={}));Et.varKinds={const:new wt.Name("const"),let:new wt.Name("let"),var:new wt.Name("var")};var Gc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof wt.Name?e:this.name(e)}name(e){return new wt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Et.Scope=Gc;var Kc=class extends wt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,wt._)`.${new wt.Name(r)}[${n}]`}};Et.ValueScopeName=Kc;var qN=(0,wt._)`\n`,ih=class extends Gc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?qN:wt.nil}}get(){return this._scope}name(e){return new Kc(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(i);if(d)return d}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,wt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=wt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Wc.Started);let d=r(u);if(d){let l=this.opts.es5?Et.varKinds.var:Et.varKinds.const;o=(0,wt._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,wt._)`${o}${d}${this.opts._n}`;else throw new oh(u);c.set(u,Wc.Completed)})}return o}};Et.ValueScope=ih});var re=D(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var pe=_i(),ur=ah(),mn=_i();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return mn._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return mn.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return mn.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return mn.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return mn.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return mn.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return mn.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return mn.Name}});var Qc=ah();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Qc.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Qc.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Qc.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Qc.varKinds}});ne.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var jr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ch=class extends jr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ur.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=eo(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},Jc=class extends jr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=eo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return Xc(e,this.rhs)}},uh=class extends Jc{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},lh=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},dh=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ph=class extends jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},mh=class extends jr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=eo(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},xi=class extends jr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(VN(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>as(e,r.names),{})}},zr=class extends xi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},fh=class extends xi{},Qs=class extends zr{};Qs.kind="else";var os=class t extends zr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Qs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(tk(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=eo(this.condition,e,r),this}get names(){let e=super.names;return Xc(e,this.condition),this.else&&as(e,this.else.names),e}};os.kind="if";var is=class extends zr{};is.kind="for";var hh=class extends is{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=eo(this.iteration,e,r),this}get names(){return as(super.names,this.iteration.names)}},gh=class extends is{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ur.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Xc(super.names,this.from);return Xc(e,this.to)}},Yc=class extends is{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=eo(this.iterable,e,r),this}get names(){return as(super.names,this.iterable.names)}},vi=class extends zr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};vi.kind="func";var bi=class extends xi{render(e){return"return "+super.render(e)}};bi.kind="return";var yh=class extends zr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&as(e,this.catch.names),this.finally&&as(e,this.finally.names),e}},Si=class extends zr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Si.kind="catch";var ki=class extends zr{render(e){return"finally"+super.render(e)}};ki.kind="finally";var _h=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
65
+ `:""},this._extScope=e,this._scope=new ur.Scope({parent:e}),this._nodes=[new fh]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new ch(e,o,n)),o}const(e,r,n){return this._def(ur.varKinds.const,e,r,n)}let(e,r,n){return this._def(ur.varKinds.let,e,r,n)}var(e,r,n){return this._def(ur.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Jc(e,r,n))}add(e,r){return this._leafNode(new uh(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new mh(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,pe.addCodeArg)(r,s));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new os(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new os(e))}else(){return this._elseNode(new Qs)}endIf(){return this._endBlockNode(os,Qs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new hh(e),r)}forRange(e,r,n,s,o=this.opts.es5?ur.varKinds.var:ur.varKinds.let){let i=this._scope.toName(e);return this._for(new gh(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ur.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(o,(0,pe._)`${i}[${a}]`),n(o)})}return this._for(new Yc("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ur.varKinds.var:ur.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Yc("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(is)}label(e){return this._leafNode(new lh(e))}break(e){return this._leafNode(new dh(e))}return(e){let r=new bi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(bi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new yh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Si(o),r(o)}return n&&(this._currNode=s.finally=new ki,this.code(n)),this._endBlockNode(Si,ki)}throw(e){return this._leafNode(new ph(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=pe.nil,n,s){return this._blockNode(new vi(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(vi)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof os))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};ne.CodeGen=_h;function as(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Xc(t,e){return e instanceof pe._CodeOrName?as(t,e.names):t}function eo(t,e,r){if(t instanceof pe.Name)return n(t);if(!s(t))return t;return new pe._Code(t._items.reduce((o,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof pe._Code&&o._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function VN(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function tk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${xh(t)}`}ne.not=tk;var WN=rk(ne.operators.AND);function GN(...t){return t.reduce(WN)}ne.and=GN;var KN=rk(ne.operators.OR);function JN(...t){return t.reduce(KN)}ne.or=JN;function rk(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${xh(e)} ${t} ${xh(r)}`}function xh(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=D(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var be=re(),YN=_i();function XN(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=XN;function QN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ok(t,e),!ik(e,t.self.RULES.all))}se.alwaysValidSchema=QN;function ok(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||uk(t,`unknown keyword: "${o}"`)}se.checkUnknownRules=ok;function ik(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=ik;function e1(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}se.schemaHasRulesButRef=e1;function t1({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,be._)`${r}`}return(0,be._)`${t}${e}${(0,be.getProperty)(n)}`}se.schemaRefOrVal=t1;function r1(t){return ak(decodeURIComponent(t))}se.unescapeFragment=r1;function n1(t){return encodeURIComponent(bh(t))}se.escapeFragment=n1;function bh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=bh;function ak(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=ak;function s1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=s1;function nk({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof be.Name?(o instanceof be.Name?t(s,o,i):e(s,o,i),i):o instanceof be.Name?(e(s,i,o),o):r(o,i);return a===be.Name&&!(c instanceof be.Name)?n(s,c):c}}se.mergeEvaluated={props:nk({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,be._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,be._)`${r} || {}`).code((0,be._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,be._)`${r} || {}`),Sh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ck}),items:nk({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,be._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,be._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ck(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,be._)`{}`);return e!==void 0&&Sh(t,r,e),r}se.evaluatedPropsToName=ck;function Sh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,be._)`${e}${(0,be.getProperty)(n)}`,!0))}se.setEvaluated=Sh;var sk={};function o1(t,e){return t.scopeValue("func",{ref:e,code:sk[e.code]||(sk[e.code]=new YN._Code(e.code))})}se.useFunc=o1;var vh;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(vh||(se.Type=vh={}));function i1(t,e,r){if(t instanceof be.Name){let n=e===vh.Num;return r?n?(0,be._)`"[" + ${t} + "]"`:(0,be._)`"['" + ${t} + "']"`:n?(0,be._)`"/" + ${t}`:(0,be._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,be.getProperty)(t).toString():"/"+bh(t)}se.getErrorPath=i1;function uk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}se.checkStrictMode=uk});var Lr=D(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var ot=re(),a1={data:new ot.Name("data"),valCxt:new ot.Name("valCxt"),instancePath:new ot.Name("instancePath"),parentData:new ot.Name("parentData"),parentDataProperty:new ot.Name("parentDataProperty"),rootData:new ot.Name("rootData"),dynamicAnchors:new ot.Name("dynamicAnchors"),vErrors:new ot.Name("vErrors"),errors:new ot.Name("errors"),this:new ot.Name("this"),self:new ot.Name("self"),scope:new ot.Name("scope"),json:new ot.Name("json"),jsonPos:new ot.Name("jsonPos"),jsonLen:new ot.Name("jsonLen"),jsonPart:new ot.Name("jsonPart")};kh.default=a1});var wi=D(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.extendErrors=it.resetErrorsCount=it.reportExtraError=it.reportError=it.keyword$DataError=it.keywordError=void 0;var fe=re(),eu=me(),ft=Lr();it.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};it.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 c1(t,e=it.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=pk(t,e,r);n??(i||a)?lk(o,c):dk(s,(0,fe._)`[${c}]`)}it.reportError=c1;function u1(t,e=it.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=pk(t,e,r);lk(s,a),o||i||dk(n,ft.default.vErrors)}it.reportExtraError=u1;function l1(t,e){t.assign(ft.default.errors,e),t.if((0,fe._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}it.resetErrorsCount=l1;function d1({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,ft.default.errors,a=>{t.const(i,(0,fe._)`${ft.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(ft.default.instancePath,o.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}it.extendErrors=d1;function lk(t,e){let r=t.const("err",e);t.if((0,fe._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${ft.default.vErrors}.push(${r})`),t.code((0,fe._)`${ft.default.errors}++`)}function dk(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var cs={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 pk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:p1(t,e,r)}function p1(t,e,r={}){let{gen:n,it:s}=t,o=[m1(s,r),f1(t,r)];return h1(t,e,o),n.object(...o)}function m1({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,eu.getErrorPath)(e,eu.Type.Str)}`:t;return[ft.default.instancePath,(0,fe.strConcat)(ft.default.instancePath,r)]}function f1({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,fe.str)`${e}/${t}`;return r&&(s=(0,fe.str)`${s}${(0,eu.getErrorPath)(r,eu.Type.Str)}`),[cs.schemaPath,s]}function h1(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([cs.keyword,s],[cs.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([cs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([cs.schema,i],[cs.parentSchema,(0,fe._)`${d}${l}`],[ft.default.data,o]),u&&n.push([cs.propertyName,u])}});var fk=D(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.boolOrEmptySchema=to.topBoolOrEmptySchema=void 0;var g1=wi(),y1=re(),_1=Lr(),x1={message:"boolean schema is false"};function v1(t){let{gen:e,schema:r,validateName:n}=t;r===!1?mk(t,!1):typeof r=="object"&&r.$async===!0?e.return(_1.default.data):(e.assign((0,y1._)`${n}.errors`,null),e.return(!0))}to.topBoolOrEmptySchema=v1;function b1(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),mk(t)):r.var(e,!0)}to.boolOrEmptySchema=b1;function mk(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,g1.reportError)(s,x1,void 0,e)}});var wh=D(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.getRules=ro.isJSONType=void 0;var S1=["string","number","integer","boolean","null","object","array"],k1=new Set(S1);function w1(t){return typeof t=="string"&&k1.has(t)}ro.isJSONType=w1;function E1(){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:{}}}ro.getRules=E1});var Eh=D(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.shouldUseRule=fn.shouldUseGroup=fn.schemaHasRulesForType=void 0;function $1({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&hk(t,n)}fn.schemaHasRulesForType=$1;function hk(t,e){return e.rules.some(r=>gk(t,r))}fn.shouldUseGroup=hk;function gk(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}fn.shouldUseRule=gk});var Ei=D(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.reportTypeError=at.checkDataTypes=at.checkDataType=at.coerceAndCheckDataType=at.getJSONTypes=at.getSchemaTypes=at.DataType=void 0;var T1=wh(),P1=Eh(),R1=wi(),ee=re(),yk=me(),no;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(no||(at.DataType=no={}));function C1(t){let e=_k(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}at.getSchemaTypes=C1;function _k(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(T1.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}at.getJSONTypes=_k;function O1(t,e){let{gen:r,data:n,opts:s}=t,o=I1(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,P1.schemaHasRulesForType)(t,e[0]));if(i){let a=Th(e,n,s.strictNumbers,no.Wrong);r.if(a,()=>{o.length?A1(t,e,o):Ph(t)})}return i}at.coerceAndCheckDataType=O1;var xk=new Set(["string","number","integer","boolean","null"]);function I1(t,e){return e?t.filter(r=>xk.has(r)||e==="array"&&r==="array"):[]}function A1(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,ee._)`typeof ${s}`),a=n.let("coerced",(0,ee._)`undefined`);o.coerceTypes==="array"&&n.if((0,ee._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,ee._)`${s}[0]`).assign(i,(0,ee._)`typeof ${s}`).if(Th(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(xk.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Ph(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(s,a),N1(t,a)});function c(u){switch(u){case"string":n.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${s}`).elseIf((0,ee._)`${s} === null`).assign(a,(0,ee._)`""`);return;case"number":n.elseIf((0,ee._)`${i} == "boolean" || ${s} === null
66
66
  || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,ee._)`+${s}`);return;case"integer":n.elseIf((0,ee._)`${i} === "boolean" || ${s} === null
67
67
  || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,ee._)`+${s}`);return;case"boolean":n.elseIf((0,ee._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,ee._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ee._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ee._)`${i} === "string" || ${i} === "number"
68
- || ${i} === "boolean" || ${s} === null`).assign(a,(0,ee._)`[${s}]`)}}}function C1({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function wh(t,e,r,n=no.Correct){let s=n===no.Correct?ee.operators.EQ:ee.operators.NEQ,o;switch(t){case"null":return(0,ee._)`${e} ${s} null`;case"array":o=(0,ee._)`Array.isArray(${e})`;break;case"object":o=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,ee._)`typeof ${e} ${s} ${t}`}return n===no.Correct?o:(0,ee.not)(o);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,r?(0,ee._)`isFinite(${e})`:ee.nil)}}at.checkDataType=wh;function Eh(t,e,r,n){if(t.length===1)return wh(t[0],e,r,n);let s,o=(0,gk.toHash)(t);if(o.array&&o.object){let i=(0,ee._)`typeof ${e} != "object"`;s=o.null?i:(0,ee._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=ee.nil;o.number&&delete o.integer;for(let i in o)s=(0,ee.and)(s,wh(i,e,r,n));return s}at.checkDataTypes=Eh;var O1={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function $h(t){let e=I1(t);(0,E1.reportError)(e,O1)}at.reportTypeError=$h;function I1(t){let{gen:e,data:r,schema:n}=t,s=(0,gk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var vk=D(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.assignDefaults=void 0;var so=re(),A1=me();function N1(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)xk(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>xk(t,o,s.default))}eu.assignDefaults=N1;function xk(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,so._)`${o}${(0,so.getProperty)(e)}`;if(s){(0,A1.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,so._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,so._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,so._)`${a} = ${(0,so.stringify)(r)}`)}});var Jt=D(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.validateUnion=ve.validateArray=ve.usePattern=ve.callValidateCode=ve.schemaProperties=ve.allSchemaProperties=ve.noPropertyInData=ve.propertyInData=ve.isOwnProperty=ve.hasPropFunc=ve.reportMissingProp=ve.checkMissingProp=ve.checkReportMissingProp=void 0;var Pe=re(),Th=me(),hn=Lr(),D1=me();function M1(t,e){let{gen:r,data:n,it:s}=t;r.if(Rh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Pe._)`${e}`},!0),t.error()})}ve.checkReportMissingProp=M1;function j1({gen:t,data:e,it:{opts:r}},n,s){return(0,Pe.or)(...n.map(o=>(0,Pe.and)(Rh(t,e,o,r.ownProperties),(0,Pe._)`${s} = ${o}`)))}ve.checkMissingProp=j1;function z1(t,e){t.setParams({missingProperty:e},!0),t.error()}ve.reportMissingProp=z1;function bk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Pe._)`Object.prototype.hasOwnProperty`})}ve.hasPropFunc=bk;function Ph(t,e,r){return(0,Pe._)`${bk(t)}.call(${e}, ${r})`}ve.isOwnProperty=Ph;function L1(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} !== undefined`;return n?(0,Pe._)`${s} && ${Ph(t,e,r)}`:s}ve.propertyInData=L1;function Rh(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} === undefined`;return n?(0,Pe.or)(s,(0,Pe.not)(Ph(t,e,r))):s}ve.noPropertyInData=Rh;function Sk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ve.allSchemaProperties=Sk;function F1(t,e){return Sk(e).filter(r=>!(0,Th.alwaysValidSchema)(t,e[r]))}ve.schemaProperties=F1;function U1({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Pe._)`${t}, ${e}, ${n}${s}`:e,l=[[hn.default.instancePath,(0,Pe.strConcat)(hn.default.instancePath,o)],[hn.default.parentData,i.parentData],[hn.default.parentDataProperty,i.parentDataProperty],[hn.default.rootData,hn.default.rootData]];i.opts.dynamicRef&&l.push([hn.default.dynamicAnchors,hn.default.dynamicAnchors]);let p=(0,Pe._)`${d}, ${r.object(...l)}`;return c!==Pe.nil?(0,Pe._)`${a}.call(${c}, ${p})`:(0,Pe._)`${a}(${p})`}ve.callValidateCode=U1;var H1=(0,Pe._)`new RegExp`;function Z1({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Pe._)`${s.code==="new RegExp"?H1:(0,D1.useFunc)(t,s)}(${r}, ${n})`})}ve.usePattern=Z1;function B1(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Pe._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Th.Type.Num},o),e.if((0,Pe.not)(o),a)})}}ve.validateArray=B1;function q1(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Th.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Pe._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Pe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ve.validateUnion=q1});var Ek=D(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.validateKeywordUsage=Er.validSchemaType=Er.funcKeywordCode=Er.macroKeywordCode=void 0;var ht=re(),cs=Lr(),V1=Jt(),W1=ki();function G1(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=wk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Er.macroKeywordCode=G1;function K1(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;Y1(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=wk(n,s,u),l=n.let("valid");t.block$data(l,p),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function p(){if(e.errors===!1)h(),e.modifying&&kk(t),g(()=>t.error());else{let _=e.async?f():m();e.modifying&&kk(t),g(()=>J1(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,ht._)`await `),v=>n.assign(l,!1).if((0,ht._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,ht._)`${v}.errors`),()=>n.throw(v))),_}function m(){let _=(0,ht._)`${d}.errors`;return n.assign(_,null),h(ht.nil),_}function h(_=e.async?(0,ht._)`await `:ht.nil){let v=c.opts.passContext?cs.default.this:cs.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,ht._)`${_}${(0,V1.callValidateCode)(t,d,v,y)}`,e.modifying)}function g(_){var v;n.if((0,ht.not)((v=e.valid)!==null&&v!==void 0?v:l),_)}}Er.funcKeywordCode=K1;function kk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function J1(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(cs.default.vErrors,(0,ht._)`${cs.default.vErrors} === null ? ${e} : ${cs.default.vErrors}.concat(${e})`).assign(cs.default.errors,(0,ht._)`${cs.default.vErrors}.length`),(0,W1.extendErrors)(t)},()=>t.error())}function Y1({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function wk(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ht.stringify)(r)})}function X1(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Er.validSchemaType=X1;function Q1({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Er.validateKeywordUsage=Q1});var Tk=D(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.extendSubschemaMode=gn.extendSubschemaData=gn.getSubschema=void 0;var $r=re(),$k=me();function eD(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}${(0,$r.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,$k.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}gn.getSubschema=eD;function tD(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,p=a.let("data",(0,$r._)`${e.data}${(0,$r.getProperty)(r)}`,!0);c(p),t.errorPath=(0,$r.str)`${u}${(0,$k.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,$r._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof $r.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);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]}}gn.extendSubschemaData=tD;function rD(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}gn.extendSubschemaMode=rD});var Ch=D((CV,Pk)=>{"use strict";Pk.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Ck=D((OV,Rk)=>{"use strict";var yn=Rk.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};tu(e,n,s,t,"",t)};yn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yn.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 tu(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in yn.arrayKeywords)for(var p=0;p<l.length;p++)tu(t,e,r,l[p],s+"/"+d+"/"+p,o,s,d,n,p)}else if(d in yn.propsKeywords){if(l&&typeof l=="object")for(var f in l)tu(t,e,r,l[f],s+"/"+d+"/"+nD(f),o,s,d,n,f)}else(d in yn.keywords||t.allKeys&&!(d in yn.skipKeywords))&&tu(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function nD(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ei=D($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getSchemaRefs=$t.resolveUrl=$t.normalizeId=$t._getFullPath=$t.getFullPath=$t.inlineRef=void 0;var sD=me(),oD=Ch(),iD=Ck(),aD=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function cD(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Oh(t):e?Ok(t)<=e:!1}$t.inlineRef=cD;var uD=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Oh(t){for(let e in t){if(uD.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Oh)||typeof r=="object"&&Oh(r))return!0}return!1}function Ok(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!aD.has(r)&&(typeof t[r]=="object"&&(0,sD.eachItem)(t[r],n=>e+=Ok(n)),e===1/0))return 1/0}return e}function Ik(t,e="",r){r!==!1&&(e=oo(e));let n=t.parse(e);return Ak(t,n)}$t.getFullPath=Ik;function Ak(t,e){return t.serialize(e).split("#")[0]+"#"}$t._getFullPath=Ak;var lD=/#\/?$/;function oo(t){return t?t.replace(lD,""):""}$t.normalizeId=oo;function dD(t,e,r){return r=oo(r),t.resolve(e,r)}$t.resolveUrl=dD;var pD=/^[a-z_][-a-z0-9._]*$/i;function mD(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=oo(t[r]||e),o={"":s},i=Ik(n,s,!1),a={},c=new Set;return iD(t,{allKeys:!0},(l,p,f,m)=>{if(m===void 0)return;let h=i+p,g=o[m];typeof l[r]=="string"&&(g=_.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),o[p]=g;function _(y){let x=this.opts.uriResolver.resolve;if(y=oo(g?x(g,y):y),c.has(y))throw d(y);c.add(y);let k=this.refs[y];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(l,k.schema,y):y!==oo(h)&&(y[0]==="#"?(u(l,a[y],y),a[y]=l):this.refs[y]=h),y}function v(y){if(typeof y=="string"){if(!pD.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(l,p,f){if(p!==void 0&&!oD(l,p))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}$t.getSchemaRefs=mD});var Pi=D(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.getData=_n.KeywordCxt=_n.validateFunctionCode=void 0;var zk=mk(),Nk=wi(),Ah=kh(),ru=wi(),fD=vk(),Ti=Ek(),Ih=Tk(),B=re(),Y=Lr(),hD=Ei(),Fr=me(),$i=ki();function gD(t){if(Uk(t)&&(Hk(t),Fk(t))){xD(t);return}Lk(t,()=>(0,zk.topBoolOrEmptySchema)(t))}_n.validateFunctionCode=gD;function Lk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,B._)`${Y.default.data}, ${Y.default.valCxt}`,n.$async,()=>{t.code((0,B._)`"use strict"; ${Dk(r,s)}`),_D(t,s),t.code(o)}):t.func(e,(0,B._)`${Y.default.data}, ${yD(s)}`,n.$async,()=>t.code(Dk(r,s)).code(o))}function yD(t){return(0,B._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,B._)`, ${Y.default.dynamicAnchors}={}`:B.nil}}={}`}function _D(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,B._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,B._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,B._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,B._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,B._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,B._)`""`),t.var(Y.default.parentData,(0,B._)`undefined`),t.var(Y.default.parentDataProperty,(0,B._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,B._)`{}`)})}function xD(t){let{schema:e,opts:r,gen:n}=t;Lk(t,()=>{r.$comment&&e.$comment&&Bk(t),wD(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&vD(t),Zk(t),TD(t)})}function vD(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,B._)`${r}.evaluated`),e.if((0,B._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${t.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${t.evaluated}.items`,(0,B._)`undefined`))}function Dk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${r} */`:B.nil}function bD(t,e){if(Uk(t)&&(Hk(t),Fk(t))){SD(t,e);return}(0,zk.boolOrEmptySchema)(t,e)}function Fk({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Uk(t){return typeof t.schema!="boolean"}function SD(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&Bk(t),ED(t),$D(t);let o=n.const("_errs",Y.default.errors);Zk(t,o),n.var(e,(0,B._)`${o} === ${Y.default.errors}`)}function Hk(t){(0,Fr.checkUnknownRules)(t),kD(t)}function Zk(t,e){if(t.opts.jtd)return Mk(t,[],!1,e);let r=(0,Nk.getSchemaTypes)(t.schema),n=(0,Nk.coerceAndCheckDataType)(t,r);Mk(t,r,!n,e)}function kD(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Fr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function wD(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Fr.checkStrictMode)(t,"default is ignored in the schema root")}function ED(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,hD.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function $D(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Bk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,B._)`${Y.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,B.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,B._)`${Y.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function TD(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,B._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,B._)`new ${s}(${Y.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,Y.default.vErrors),o.unevaluated&&PD(t),e.return((0,B._)`${Y.default.errors} === 0`))}function PD({gen:t,evaluated:e,props:r,items:n}){r instanceof B.Name&&t.assign((0,B._)`${e}.props`,r),n instanceof B.Name&&t.assign((0,B._)`${e}.items`,n)}function Mk(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Fr.schemaHasRulesButRef)(o,d))){s.block(()=>Vk(t,"$ref",d.all.$ref.definition));return}c.jtd||RD(t,e),s.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,Ah.shouldUseGroup)(o,p)&&(p.type?(s.if((0,ru.checkDataType)(p.type,i,c.strictNumbers)),jk(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,ru.reportTypeError)(t)),s.endIf()):jk(t,p),a||s.if((0,B._)`${Y.default.errors} === ${n||0}`))}}function jk(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,fD.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Ah.shouldUseRule)(n,o)&&Vk(t,o.keyword,o.definition,e.type)})}function RD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(CD(t,e),t.opts.allowUnionTypes||OD(t,e),ID(t,t.dataTypes))}function CD(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{qk(t.dataTypes,r)||Nh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),ND(t,e)}}function OD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Nh(t,"use allowUnionTypes to allow union type keyword")}function ID(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Ah.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>AD(e,i))&&Nh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function AD(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function qk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function ND(t,e){let r=[];for(let n of t.dataTypes)qk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Nh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Fr.checkStrictMode)(t,e,t.opts.strictTypes)}var nu=class{constructor(e,r,n){if((0,Ti.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Fr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Wk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ti.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Y.default.errors))}result(e,r,n){this.failResult((0,B.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,B.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,B._)`${r} !== undefined && (${(0,B.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?$i.reportExtraError:$i.reportError)(this,this.def.error,r)}$dataError(){(0,$i.reportError)(this,this.def.$dataError||$i.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$i.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=B.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=B.nil,r=B.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,B.or)((0,B._)`${s} === undefined`,r)),e!==B.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,B.or)(i(),a());function i(){if(n.length){if(!(r instanceof B.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,B._)`${(0,ru.checkDataTypes)(c,r,o.opts.strictNumbers,ru.DataType.Wrong)}`}return B.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,B._)`!${c}(${r})`}return B.nil}}subschema(e,r){let n=(0,Ih.getSubschema)(this.it,e);(0,Ih.extendSubschemaData)(n,this.it,e),(0,Ih.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return bD(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Fr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Fr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,B.Name)),!0}};_n.KeywordCxt=nu;function Vk(t,e,r,n){let s=new nu(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Ti.funcKeywordCode)(s,r):"macro"in r?(0,Ti.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Ti.funcKeywordCode)(s,r)}var DD=/^\/(?:[^~]|~0|~1)*$/,MD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Wk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!DD.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=MD.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(o=r[e-d],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,B._)`${o}${(0,B.getProperty)((0,Fr.unescapeJsonPointer)(u))}`,i=(0,B._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}_n.getData=Wk});var su=D(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var Dh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Mh.default=Dh});var Ri=D(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var jh=Ei(),zh=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,jh.resolveUrl)(e,r,n),this.missingSchema=(0,jh.normalizeId)((0,jh.getFullPath)(e,this.missingRef))}};Lh.default=zh});var iu=D(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;var lr=re(),jD=su(),us=Lr(),dr=Ei(),Gk=me(),zD=Pi(),io=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,dr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Yt.SchemaEnv=io;function Uh(t){let e=Kk.call(this,t);if(e)return e;let r=(0,dr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new lr.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:jD.default,code:(0,lr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:us.default.data,parentData:us.default.parentData,parentDataProperty:us.default.parentDataProperty,dataNames:[us.default.data],dataPathArr:[lr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,lr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:lr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,lr._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,zD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(us.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${us.default.self}`,`${us.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:h}=u;f.evaluated={props:m instanceof lr.Name?void 0:m,items:h instanceof lr.Name?void 0:h,dynamicProps:m instanceof lr.Name,dynamicItems:h instanceof lr.Name},f.source&&(f.source.evaluated=(0,lr.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Yt.compileSchema=Uh;function LD(t,e,r){var n;r=(0,dr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=HD.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new io({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=FD.call(this,o)}Yt.resolveRef=LD;function FD(t){return(0,dr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Uh.call(this,t)}function Kk(t){for(let e of this._compilations)if(UD(e,t))return e}Yt.getCompilingSchema=Kk;function UD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function HD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ou.call(this,t,e)}function ou(t,e){let r=this.opts.uriResolver.parse(e),n=(0,dr._getFullPath)(this.opts.uriResolver,r),s=(0,dr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Fh.call(this,r,t);let o=(0,dr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=ou.call(this,t,i);return typeof a?.schema!="object"?void 0:Fh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Uh.call(this,i),o===(0,dr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,dr.resolveUrl)(this.opts.uriResolver,s,u)),new io({schema:a,schemaId:c,root:t,baseId:s})}return Fh.call(this,r,i)}}Yt.resolveSchema=ou;var ZD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Fh(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Gk.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!ZD.has(a)&&u&&(e=(0,dr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Gk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,dr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=ou.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new io({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Jk=D((jV,BD)=>{BD.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 Zh=D((zV,e0)=>{"use strict";var qD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Xk=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Hh(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var VD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Yk(t){return t.length=0,!0}function WD(t,e,r){if(t.length){let n=Hh(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function GD(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=WD;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=Yk}else{s.push(u);continue}}return s.length&&(a===Yk?r.zone=s.join(""):i?n.push(s.join("")):n.push(Hh(s))),r.address=n.join(""),r}function Qk(t){if(KD(t,":")<2)return{host:t,isIPV6:!1};let e=GD(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function KD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function JD(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function YD(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function XD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Xk(r)){let n=Qk(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}e0.exports={nonSimpleDomain:VD,recomposeAuthority:XD,normalizeComponentEncoding:YD,removeDotSegments:JD,isIPv4:Xk,isUUID:qD,normalizeIPv6:Qk,stringArrayToHexStripped:Hh}});var o0=D((LV,s0)=>{"use strict";var{isUUID:QD}=Zh(),eM=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,tM=["http","https","ws","wss","urn","urn:uuid"];function rM(t){return tM.indexOf(t)!==-1}function Bh(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 t0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function r0(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 nM(t){return t.secure=Bh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function sM(t){if((t.port===(Bh(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function oM(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(eM);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=qh(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function iM(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=qh(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function aM(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!QD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function cM(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var n0={scheme:"http",domainHost:!0,parse:t0,serialize:r0},uM={scheme:"https",domainHost:n0.domainHost,parse:t0,serialize:r0},au={scheme:"ws",domainHost:!0,parse:nM,serialize:sM},lM={scheme:"wss",domainHost:au.domainHost,parse:au.parse,serialize:au.serialize},dM={scheme:"urn",parse:oM,serialize:iM,skipNormalize:!0},pM={scheme:"urn:uuid",parse:aM,serialize:cM,skipNormalize:!0},cu={http:n0,https:uM,ws:au,wss:lM,urn:dM,"urn:uuid":pM};Object.setPrototypeOf(cu,null);function qh(t){return t&&(cu[t]||cu[t.toLowerCase()])||void 0}s0.exports={wsIsSecure:Bh,SCHEMES:cu,isValidSchemeName:rM,getSchemeHandler:qh}});var c0=D((FV,lu)=>{"use strict";var{normalizeIPv6:mM,removeDotSegments:Ci,recomposeAuthority:fM,normalizeComponentEncoding:uu,isIPv4:hM,nonSimpleDomain:gM}=Zh(),{SCHEMES:yM,getSchemeHandler:i0}=o0();function _M(t,e){return typeof t=="string"?t=Tr(Ur(t,e),e):typeof t=="object"&&(t=Ur(Tr(t,e),e)),t}function xM(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=a0(Ur(t,n),Ur(e,n),n,!0);return n.skipEscape=!0,Tr(s,n)}function a0(t,e,r,n){let s={};return n||(t=Ur(Tr(t,r),r),e=Ur(Tr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ci(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ci(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ci(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ci(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function vM(t,e,r){return typeof t=="string"?(t=unescape(t),t=Tr(uu(Ur(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Tr(uu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Tr(uu(Ur(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Tr(uu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Tr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],o=i0(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=fM(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Ci(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var bM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ur(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(bM);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(hM(n.host)===!1){let c=mM(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=i0(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&gM(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Vh={SCHEMES:yM,normalize:_M,resolve:xM,resolveComponent:a0,equal:vM,serialize:Tr,parse:Ur};lu.exports=Vh;lu.exports.default=Vh;lu.exports.fastUri=Vh});var l0=D(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var u0=c0();u0.code='require("ajv/dist/runtime/uri").default';Wh.default=u0});var _0=D(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.CodeGen=et.Name=et.nil=et.stringify=et.str=et._=et.KeywordCxt=void 0;var SM=Pi();Object.defineProperty(et,"KeywordCxt",{enumerable:!0,get:function(){return SM.KeywordCxt}});var ao=re();Object.defineProperty(et,"_",{enumerable:!0,get:function(){return ao._}});Object.defineProperty(et,"str",{enumerable:!0,get:function(){return ao.str}});Object.defineProperty(et,"stringify",{enumerable:!0,get:function(){return ao.stringify}});Object.defineProperty(et,"nil",{enumerable:!0,get:function(){return ao.nil}});Object.defineProperty(et,"Name",{enumerable:!0,get:function(){return ao.Name}});Object.defineProperty(et,"CodeGen",{enumerable:!0,get:function(){return ao.CodeGen}});var kM=su(),h0=Ri(),wM=Sh(),Oi=iu(),EM=re(),Ii=Ei(),du=wi(),Kh=me(),d0=Jk(),$M=l0(),g0=(t,e)=>new RegExp(t,e);g0.code="new RegExp";var TM=["removeAdditional","useDefaults","coerceTypes"],PM=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),RM={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."},CM={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},p0=200;function OM(t){var e,r,n,s,o,i,a,c,u,d,l,p,f,m,h,g,_,v,y,x,k,R,$,P,j;let T=t.strict,C=(e=t.code)===null||e===void 0?void 0:e.optimize,L=C===!0||C===void 0?1:C||0,X=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:g0,ae=(s=t.uriResolver)!==null&&s!==void 0?s:$M.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:T)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:T)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:T)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=t.strictTuples)!==null&&l!==void 0?l:T)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:T)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:L,regExp:X}:{optimize:L,regExp:X},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:p0,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:p0,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(R=t.validateSchema)!==null&&R!==void 0?R:!0,validateFormats:($=t.validateFormats)!==null&&$!==void 0?$:!0,unicodeRegExp:(P=t.unicodeRegExp)!==null&&P!==void 0?P:!0,int32range:(j=t.int32range)!==null&&j!==void 0?j:!0,uriResolver:ae}}var Ai=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,...OM(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new EM.ValueScope({scope:{},prefixes:PM,es5:r,lines:n}),this.logger=jM(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,wM.getRules)(),m0.call(this,RM,e,"NOT SUPPORTED"),m0.call(this,CM,e,"DEPRECATED","warn"),this._metaOpts=DM.call(this),e.formats&&AM.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&NM.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),IM.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=d0;n==="id"&&(s={...d0},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,l){await o.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof h0.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await o.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Ii.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=f0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Oi.SchemaEnv({schema:{},schemaId:n});if(r=Oi.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=f0.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Ii.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(LM.call(this,n,r),!r)return(0,Kh.eachItem)(n,o=>Gh.call(this,o)),this;UM.call(this,r);let s={...r,type:(0,du.getJSONTypes)(r.type),schemaType:(0,du.getJSONTypes)(r.schemaType)};return(0,Kh.eachItem)(n,s.type.length===0?o=>Gh.call(this,o,s):o=>s.type.forEach(i=>Gh.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=y0(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Ii.normalizeId)(i||n);let u=Ii.getSchemaRefs.call(this,e,n);return c=new Oi.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&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):Oi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Oi.compileSchema.call(this,e)}finally{this.opts=r}}};Ai.ValidationError=kM.default;Ai.MissingRefError=h0.default;et.default=Ai;function m0(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function f0(t){return t=(0,Ii.normalizeId)(t),this.schemas[t]||this.refs[t]}function IM(){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 AM(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function NM(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function DM(){let t={...this.opts};for(let e of TM)delete t[e];return t}var MM={log(){},warn(){},error(){}};function jM(t){if(t===!1)return MM;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 zM=/^[a-z_$][a-z0-9_$:-]*$/i;function LM(t,e){let{RULES:r}=this;if((0,Kh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!zM.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Gh(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,du.getJSONTypes)(e.type),schemaType:(0,du.getJSONTypes)(e.schemaType)}};e.before?FM.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function FM(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function UM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=y0(e)),t.validateSchema=this.compile(e,!0))}var HM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function y0(t){return{anyOf:[t,HM]}}});var x0=D(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});var ZM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Jh.default=ZM});var k0=D(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.callRef=ls.getValidate=void 0;var BM=Ri(),v0=Jt(),Tt=re(),co=Lr(),b0=iu(),pu=me(),qM={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return l();let d=b0.resolveRef.call(c,u,s,r);if(d===void 0)throw new BM.default(n.opts.uriResolver,s,r);if(d instanceof b0.SchemaEnv)return p(d);return f(d);function l(){if(o===u)return mu(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return mu(t,(0,Tt._)`${m}.validate`,u,u.$async)}function p(m){let h=S0(t,m);mu(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Tt.stringify)(m)}:{ref:m}),g=e.name("valid"),_=t.subschema({schema:m,dataTypes:[],schemaPath:Tt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(_),t.ok(g)}}};function S0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Tt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ls.getValidate=S0;function mu(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?co.default.this:Tt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,Tt._)`await ${(0,v0.callValidateCode)(t,e,u)}`),f(e),i||s.assign(m,!0)},h=>{s.if((0,Tt._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),p(h),i||s.assign(m,!1)}),t.ok(m)}function l(){t.result((0,v0.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,Tt._)`${m}.errors`;s.assign(co.default.vErrors,(0,Tt._)`${co.default.vErrors} === null ? ${h} : ${co.default.vErrors}.concat(${h})`),s.assign(co.default.errors,(0,Tt._)`${co.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=pu.mergeEvaluated.props(s,g.props,o.props));else{let _=s.var("props",(0,Tt._)`${m}.evaluated.props`);o.props=pu.mergeEvaluated.props(s,_,o.props,Tt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=pu.mergeEvaluated.items(s,g.items,o.items));else{let _=s.var("items",(0,Tt._)`${m}.evaluated.items`);o.items=pu.mergeEvaluated.items(s,_,o.items,Tt.Name)}}}ls.callRef=mu;ls.default=qM});var w0=D(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var VM=x0(),WM=k0(),GM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",VM.default,WM.default];Yh.default=GM});var E0=D(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var fu=re(),xn=fu.operators,hu={maximum:{okStr:"<=",ok:xn.LTE,fail:xn.GT},minimum:{okStr:">=",ok:xn.GTE,fail:xn.LT},exclusiveMaximum:{okStr:"<",ok:xn.LT,fail:xn.GTE},exclusiveMinimum:{okStr:">",ok:xn.GT,fail:xn.LTE}},KM={message:({keyword:t,schemaCode:e})=>(0,fu.str)`must be ${hu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,fu._)`{comparison: ${hu[t].okStr}, limit: ${e}}`},JM={keyword:Object.keys(hu),type:"number",schemaType:"number",$data:!0,error:KM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,fu._)`${r} ${hu[e].fail} ${n} || isNaN(${r})`)}};Xh.default=JM});var $0=D(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});var Ni=re(),YM={message:({schemaCode:t})=>(0,Ni.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ni._)`{multipleOf: ${t}}`},XM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:YM,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Ni._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Ni._)`${i} !== parseInt(${i})`;t.fail$data((0,Ni._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Qh.default=XM});var P0=D(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});function T0(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}eg.default=T0;T0.code='require("ajv/dist/runtime/ucs2length").default'});var R0=D(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var ds=re(),QM=me(),ej=P0(),tj={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ds.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ds._)`{limit: ${t}}`},rj={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:tj,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ds.operators.GT:ds.operators.LT,i=s.opts.unicode===!1?(0,ds._)`${r}.length`:(0,ds._)`${(0,QM.useFunc)(t.gen,ej.default)}(${r})`;t.fail$data((0,ds._)`${i} ${o} ${n}`)}};tg.default=rj});var C0=D(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var nj=Jt(),sj=me(),uo=re(),oj={message:({schemaCode:t})=>(0,uo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,uo._)`{pattern: ${t}}`},ij={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:oj,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,uo._)`new RegExp`:(0,sj.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,uo._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,uo._)`!${d}`)}else{let c=(0,nj.usePattern)(t,s);t.fail$data((0,uo._)`!${c}.test(${r})`)}}};rg.default=ij});var O0=D(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var Di=re(),aj={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Di.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Di._)`{limit: ${t}}`},cj={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:aj,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Di.operators.GT:Di.operators.LT;t.fail$data((0,Di._)`Object.keys(${r}).length ${s} ${n}`)}};ng.default=cj});var I0=D(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var Mi=Jt(),ji=re(),uj=me(),lj={message:({params:{missingProperty:t}})=>(0,ji.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ji._)`{missingProperty: ${t}}`},dj={keyword:"required",type:"object",schemaType:"array",$data:!0,error:lj,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,uj.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(ji.nil,l);else for(let f of r)(0,Mi.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Mi.checkMissingProp)(t,r,f)),(0,Mi.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Mi.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Mi.propertyInData)(e,s,f,a.ownProperties)),e.if((0,ji.not)(m),()=>{t.error(),e.break()})},ji.nil)}}};sg.default=dj});var A0=D(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});var zi=re(),pj={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,zi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,zi._)`{limit: ${t}}`},mj={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:pj,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?zi.operators.GT:zi.operators.LT;t.fail$data((0,zi._)`${r}.length ${s} ${n}`)}};og.default=mj});var gu=D(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var N0=Ch();N0.code='require("ajv/dist/runtime/equal").default';ig.default=N0});var D0=D(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var ag=wi(),tt=re(),fj=me(),hj=gu(),gj={message:({params:{i:t,j:e}})=>(0,tt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,tt._)`{i: ${t}, j: ${e}}`},yj={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:gj,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,ag.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,tt._)`${i} === false`),t.ok(c);function d(){let m=e.let("i",(0,tt._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,tt._)`${m} > 1`,()=>(l()?p:f)(m,h))}function l(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let g=e.name("item"),_=(0,ag.checkDataTypes)(u,g,a.opts.strictNumbers,ag.DataType.Wrong),v=e.const("indices",(0,tt._)`{}`);e.for((0,tt._)`;${m}--;`,()=>{e.let(g,(0,tt._)`${r}[${m}]`),e.if(_,(0,tt._)`continue`),u.length>1&&e.if((0,tt._)`typeof ${g} == "string"`,(0,tt._)`${g} += "_"`),e.if((0,tt._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,tt._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,tt._)`${v}[${g}] = ${m}`)})}function f(m,h){let g=(0,fj.useFunc)(e,hj.default),_=e.name("outer");e.label(_).for((0,tt._)`;${m}--;`,()=>e.for((0,tt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,tt._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};cg.default=yj});var M0=D(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var ug=re(),_j=me(),xj=gu(),vj={message:"must be equal to constant",params:({schemaCode:t})=>(0,ug._)`{allowedValue: ${t}}`},bj={keyword:"const",$data:!0,error:vj,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,ug._)`!${(0,_j.useFunc)(e,xj.default)}(${r}, ${s})`):t.fail((0,ug._)`${o} !== ${r}`)}};lg.default=bj});var j0=D(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var Li=re(),Sj=me(),kj=gu(),wj={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Li._)`{allowedValues: ${t}}`},Ej={keyword:"enum",schemaType:"array",$data:!0,error:wj,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,Sj.useFunc)(e,kj.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);d=(0,Li.or)(...s.map((m,h)=>p(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,f=>e.if((0,Li._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Li._)`${u()}(${r}, ${f}[${m}])`:(0,Li._)`${r} === ${h}`}}};dg.default=Ej});var z0=D(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var $j=E0(),Tj=$0(),Pj=R0(),Rj=C0(),Cj=O0(),Oj=I0(),Ij=A0(),Aj=D0(),Nj=M0(),Dj=j0(),Mj=[$j.default,Tj.default,Pj.default,Rj.default,Cj.default,Oj.default,Ij.default,Aj.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Nj.default,Dj.default];pg.default=Mj});var fg=D(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.validateAdditionalItems=void 0;var ps=re(),mg=me(),jj={message:({params:{len:t}})=>(0,ps.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ps._)`{limit: ${t}}`},zj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:jj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,mg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}L0(t,n)}};function L0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,ps._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ps._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,mg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,ps._)`${a} <= ${e.length}`);r.if((0,ps.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:mg.Type.Num},u),i.allErrors||r.if((0,ps.not)(u),()=>r.break())})}}Fi.validateAdditionalItems=L0;Fi.default=zj});var hg=D(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.validateTuple=void 0;var F0=re(),yu=me(),Lj=Jt(),Fj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return U0(t,"additionalItems",e);r.items=!0,!(0,yu.alwaysValidSchema)(r,e)&&t.ok((0,Lj.validateArray)(t))}};function U0(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;d(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=yu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,F0._)`${o}.length`);r.forEach((l,p)=>{(0,yu.alwaysValidSchema)(a,l)||(n.if((0,F0._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function d(l){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===l.minItems&&(m===l.maxItems||l[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,yu.checkStrictMode)(a,g,p.strictTuples)}}}Ui.validateTuple=U0;Ui.default=Fj});var H0=D(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var Uj=hg(),Hj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Uj.validateTuple)(t,"items")};gg.default=Hj});var B0=D(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var Z0=re(),Zj=me(),Bj=Jt(),qj=fg(),Vj={message:({params:{len:t}})=>(0,Z0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Z0._)`{limit: ${t}}`},Wj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Vj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Zj.alwaysValidSchema)(n,e)&&(s?(0,qj.validateAdditionalItems)(t,s):t.ok((0,Bj.validateArray)(t)))}};yg.default=Wj});var q0=D(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var Xt=re(),_u=me(),Gj={message:({params:{min:t,max:e}})=>e===void 0?(0,Xt.str)`must contain at least ${t} valid item(s)`:(0,Xt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Xt._)`{minContains: ${t}}`:(0,Xt._)`{minContains: ${t}, maxContains: ${e}}`},Kj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Gj,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,Xt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,_u.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,_u.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,_u.alwaysValidSchema)(o,r)){let h=(0,Xt._)`${d} >= ${i}`;a!==void 0&&(h=(0,Xt._)`${h} && ${d} <= ${a}`),t.pass(h);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Xt._)`${s}.length > 0`,p)):(e.let(l,!1),p()),t.result(l,()=>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,d,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:_u.Type.Num,compositeRule:!0},h),g()})}function m(h){e.code((0,Xt._)`${h}++`),a===void 0?e.if((0,Xt._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Xt._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Xt._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};_g.default=Kj});var G0=D(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.validateSchemaDeps=Pr.validatePropertyDeps=Pr.error=void 0;var xg=re(),Jj=me(),Hi=Jt();Pr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,xg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,xg._)`{property: ${t},
68
+ || ${i} === "boolean" || ${s} === null`).assign(a,(0,ee._)`[${s}]`)}}}function N1({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function $h(t,e,r,n=no.Correct){let s=n===no.Correct?ee.operators.EQ:ee.operators.NEQ,o;switch(t){case"null":return(0,ee._)`${e} ${s} null`;case"array":o=(0,ee._)`Array.isArray(${e})`;break;case"object":o=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,ee._)`typeof ${e} ${s} ${t}`}return n===no.Correct?o:(0,ee.not)(o);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,r?(0,ee._)`isFinite(${e})`:ee.nil)}}at.checkDataType=$h;function Th(t,e,r,n){if(t.length===1)return $h(t[0],e,r,n);let s,o=(0,yk.toHash)(t);if(o.array&&o.object){let i=(0,ee._)`typeof ${e} != "object"`;s=o.null?i:(0,ee._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=ee.nil;o.number&&delete o.integer;for(let i in o)s=(0,ee.and)(s,$h(i,e,r,n));return s}at.checkDataTypes=Th;var D1={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function Ph(t){let e=M1(t);(0,R1.reportError)(e,D1)}at.reportTypeError=Ph;function M1(t){let{gen:e,data:r,schema:n}=t,s=(0,yk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var bk=D(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.assignDefaults=void 0;var so=re(),j1=me();function z1(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)vk(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>vk(t,o,s.default))}tu.assignDefaults=z1;function vk(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,so._)`${o}${(0,so.getProperty)(e)}`;if(s){(0,j1.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,so._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,so._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,so._)`${a} = ${(0,so.stringify)(r)}`)}});var Jt=D(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.validateUnion=ve.validateArray=ve.usePattern=ve.callValidateCode=ve.schemaProperties=ve.allSchemaProperties=ve.noPropertyInData=ve.propertyInData=ve.isOwnProperty=ve.hasPropFunc=ve.reportMissingProp=ve.checkMissingProp=ve.checkReportMissingProp=void 0;var Pe=re(),Rh=me(),hn=Lr(),L1=me();function F1(t,e){let{gen:r,data:n,it:s}=t;r.if(Oh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Pe._)`${e}`},!0),t.error()})}ve.checkReportMissingProp=F1;function U1({gen:t,data:e,it:{opts:r}},n,s){return(0,Pe.or)(...n.map(o=>(0,Pe.and)(Oh(t,e,o,r.ownProperties),(0,Pe._)`${s} = ${o}`)))}ve.checkMissingProp=U1;function H1(t,e){t.setParams({missingProperty:e},!0),t.error()}ve.reportMissingProp=H1;function Sk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Pe._)`Object.prototype.hasOwnProperty`})}ve.hasPropFunc=Sk;function Ch(t,e,r){return(0,Pe._)`${Sk(t)}.call(${e}, ${r})`}ve.isOwnProperty=Ch;function Z1(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} !== undefined`;return n?(0,Pe._)`${s} && ${Ch(t,e,r)}`:s}ve.propertyInData=Z1;function Oh(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} === undefined`;return n?(0,Pe.or)(s,(0,Pe.not)(Ch(t,e,r))):s}ve.noPropertyInData=Oh;function kk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ve.allSchemaProperties=kk;function B1(t,e){return kk(e).filter(r=>!(0,Rh.alwaysValidSchema)(t,e[r]))}ve.schemaProperties=B1;function q1({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Pe._)`${t}, ${e}, ${n}${s}`:e,l=[[hn.default.instancePath,(0,Pe.strConcat)(hn.default.instancePath,o)],[hn.default.parentData,i.parentData],[hn.default.parentDataProperty,i.parentDataProperty],[hn.default.rootData,hn.default.rootData]];i.opts.dynamicRef&&l.push([hn.default.dynamicAnchors,hn.default.dynamicAnchors]);let p=(0,Pe._)`${d}, ${r.object(...l)}`;return c!==Pe.nil?(0,Pe._)`${a}.call(${c}, ${p})`:(0,Pe._)`${a}(${p})`}ve.callValidateCode=q1;var V1=(0,Pe._)`new RegExp`;function W1({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Pe._)`${s.code==="new RegExp"?V1:(0,L1.useFunc)(t,s)}(${r}, ${n})`})}ve.usePattern=W1;function G1(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Pe._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Rh.Type.Num},o),e.if((0,Pe.not)(o),a)})}}ve.validateArray=G1;function K1(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Rh.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Pe._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Pe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ve.validateUnion=K1});var $k=D(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.validateKeywordUsage=Er.validSchemaType=Er.funcKeywordCode=Er.macroKeywordCode=void 0;var ht=re(),us=Lr(),J1=Jt(),Y1=wi();function X1(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=Ek(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Er.macroKeywordCode=X1;function Q1(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;tD(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=Ek(n,s,u),l=n.let("valid");t.block$data(l,p),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function p(){if(e.errors===!1)h(),e.modifying&&wk(t),g(()=>t.error());else{let _=e.async?f():m();e.modifying&&wk(t),g(()=>eD(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,ht._)`await `),v=>n.assign(l,!1).if((0,ht._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,ht._)`${v}.errors`),()=>n.throw(v))),_}function m(){let _=(0,ht._)`${d}.errors`;return n.assign(_,null),h(ht.nil),_}function h(_=e.async?(0,ht._)`await `:ht.nil){let v=c.opts.passContext?us.default.this:us.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,ht._)`${_}${(0,J1.callValidateCode)(t,d,v,y)}`,e.modifying)}function g(_){var v;n.if((0,ht.not)((v=e.valid)!==null&&v!==void 0?v:l),_)}}Er.funcKeywordCode=Q1;function wk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function eD(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(us.default.vErrors,(0,ht._)`${us.default.vErrors} === null ? ${e} : ${us.default.vErrors}.concat(${e})`).assign(us.default.errors,(0,ht._)`${us.default.vErrors}.length`),(0,Y1.extendErrors)(t)},()=>t.error())}function tD({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ek(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ht.stringify)(r)})}function rD(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Er.validSchemaType=rD;function nD({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Er.validateKeywordUsage=nD});var Pk=D(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.extendSubschemaMode=gn.extendSubschemaData=gn.getSubschema=void 0;var $r=re(),Tk=me();function sD(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}${(0,$r.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Tk.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}gn.getSubschema=sD;function oD(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,p=a.let("data",(0,$r._)`${e.data}${(0,$r.getProperty)(r)}`,!0);c(p),t.errorPath=(0,$r.str)`${u}${(0,Tk.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,$r._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof $r.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);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]}}gn.extendSubschemaData=oD;function iD(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}gn.extendSubschemaMode=iD});var Ih=D((MV,Rk)=>{"use strict";Rk.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Ok=D((jV,Ck)=>{"use strict";var yn=Ck.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};ru(e,n,s,t,"",t)};yn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yn.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 ru(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in yn.arrayKeywords)for(var p=0;p<l.length;p++)ru(t,e,r,l[p],s+"/"+d+"/"+p,o,s,d,n,p)}else if(d in yn.propsKeywords){if(l&&typeof l=="object")for(var f in l)ru(t,e,r,l[f],s+"/"+d+"/"+aD(f),o,s,d,n,f)}else(d in yn.keywords||t.allKeys&&!(d in yn.skipKeywords))&&ru(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function aD(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var $i=D($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getSchemaRefs=$t.resolveUrl=$t.normalizeId=$t._getFullPath=$t.getFullPath=$t.inlineRef=void 0;var cD=me(),uD=Ih(),lD=Ok(),dD=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function pD(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ah(t):e?Ik(t)<=e:!1}$t.inlineRef=pD;var mD=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ah(t){for(let e in t){if(mD.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Ah)||typeof r=="object"&&Ah(r))return!0}return!1}function Ik(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!dD.has(r)&&(typeof t[r]=="object"&&(0,cD.eachItem)(t[r],n=>e+=Ik(n)),e===1/0))return 1/0}return e}function Ak(t,e="",r){r!==!1&&(e=oo(e));let n=t.parse(e);return Nk(t,n)}$t.getFullPath=Ak;function Nk(t,e){return t.serialize(e).split("#")[0]+"#"}$t._getFullPath=Nk;var fD=/#\/?$/;function oo(t){return t?t.replace(fD,""):""}$t.normalizeId=oo;function hD(t,e,r){return r=oo(r),t.resolve(e,r)}$t.resolveUrl=hD;var gD=/^[a-z_][-a-z0-9._]*$/i;function yD(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=oo(t[r]||e),o={"":s},i=Ak(n,s,!1),a={},c=new Set;return lD(t,{allKeys:!0},(l,p,f,m)=>{if(m===void 0)return;let h=i+p,g=o[m];typeof l[r]=="string"&&(g=_.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),o[p]=g;function _(y){let x=this.opts.uriResolver.resolve;if(y=oo(g?x(g,y):y),c.has(y))throw d(y);c.add(y);let k=this.refs[y];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(l,k.schema,y):y!==oo(h)&&(y[0]==="#"?(u(l,a[y],y),a[y]=l):this.refs[y]=h),y}function v(y){if(typeof y=="string"){if(!gD.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(l,p,f){if(p!==void 0&&!uD(l,p))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}$t.getSchemaRefs=yD});var Ri=D(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.getData=_n.KeywordCxt=_n.validateFunctionCode=void 0;var Lk=fk(),Dk=Ei(),Dh=Eh(),nu=Ei(),_D=bk(),Pi=$k(),Nh=Pk(),B=re(),Y=Lr(),xD=$i(),Fr=me(),Ti=wi();function vD(t){if(Hk(t)&&(Zk(t),Uk(t))){kD(t);return}Fk(t,()=>(0,Lk.topBoolOrEmptySchema)(t))}_n.validateFunctionCode=vD;function Fk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,B._)`${Y.default.data}, ${Y.default.valCxt}`,n.$async,()=>{t.code((0,B._)`"use strict"; ${Mk(r,s)}`),SD(t,s),t.code(o)}):t.func(e,(0,B._)`${Y.default.data}, ${bD(s)}`,n.$async,()=>t.code(Mk(r,s)).code(o))}function bD(t){return(0,B._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,B._)`, ${Y.default.dynamicAnchors}={}`:B.nil}}={}`}function SD(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,B._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,B._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,B._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,B._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,B._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,B._)`""`),t.var(Y.default.parentData,(0,B._)`undefined`),t.var(Y.default.parentDataProperty,(0,B._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,B._)`{}`)})}function kD(t){let{schema:e,opts:r,gen:n}=t;Fk(t,()=>{r.$comment&&e.$comment&&qk(t),PD(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&wD(t),Bk(t),OD(t)})}function wD(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,B._)`${r}.evaluated`),e.if((0,B._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${t.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${t.evaluated}.items`,(0,B._)`undefined`))}function Mk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${r} */`:B.nil}function ED(t,e){if(Hk(t)&&(Zk(t),Uk(t))){$D(t,e);return}(0,Lk.boolOrEmptySchema)(t,e)}function Uk({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Hk(t){return typeof t.schema!="boolean"}function $D(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&qk(t),RD(t),CD(t);let o=n.const("_errs",Y.default.errors);Bk(t,o),n.var(e,(0,B._)`${o} === ${Y.default.errors}`)}function Zk(t){(0,Fr.checkUnknownRules)(t),TD(t)}function Bk(t,e){if(t.opts.jtd)return jk(t,[],!1,e);let r=(0,Dk.getSchemaTypes)(t.schema),n=(0,Dk.coerceAndCheckDataType)(t,r);jk(t,r,!n,e)}function TD(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Fr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function PD(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Fr.checkStrictMode)(t,"default is ignored in the schema root")}function RD(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,xD.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function CD(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function qk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,B._)`${Y.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,B.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,B._)`${Y.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function OD(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,B._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,B._)`new ${s}(${Y.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,Y.default.vErrors),o.unevaluated&&ID(t),e.return((0,B._)`${Y.default.errors} === 0`))}function ID({gen:t,evaluated:e,props:r,items:n}){r instanceof B.Name&&t.assign((0,B._)`${e}.props`,r),n instanceof B.Name&&t.assign((0,B._)`${e}.items`,n)}function jk(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Fr.schemaHasRulesButRef)(o,d))){s.block(()=>Wk(t,"$ref",d.all.$ref.definition));return}c.jtd||AD(t,e),s.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,Dh.shouldUseGroup)(o,p)&&(p.type?(s.if((0,nu.checkDataType)(p.type,i,c.strictNumbers)),zk(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,nu.reportTypeError)(t)),s.endIf()):zk(t,p),a||s.if((0,B._)`${Y.default.errors} === ${n||0}`))}}function zk(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,_D.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Dh.shouldUseRule)(n,o)&&Wk(t,o.keyword,o.definition,e.type)})}function AD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(ND(t,e),t.opts.allowUnionTypes||DD(t,e),MD(t,t.dataTypes))}function ND(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Vk(t.dataTypes,r)||Mh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),zD(t,e)}}function DD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Mh(t,"use allowUnionTypes to allow union type keyword")}function MD(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Dh.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>jD(e,i))&&Mh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function jD(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Vk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function zD(t,e){let r=[];for(let n of t.dataTypes)Vk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Mh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Fr.checkStrictMode)(t,e,t.opts.strictTypes)}var su=class{constructor(e,r,n){if((0,Pi.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Fr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Gk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Pi.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Y.default.errors))}result(e,r,n){this.failResult((0,B.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,B.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,B._)`${r} !== undefined && (${(0,B.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Ti.reportExtraError:Ti.reportError)(this,this.def.error,r)}$dataError(){(0,Ti.reportError)(this,this.def.$dataError||Ti.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ti.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=B.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=B.nil,r=B.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,B.or)((0,B._)`${s} === undefined`,r)),e!==B.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,B.or)(i(),a());function i(){if(n.length){if(!(r instanceof B.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,B._)`${(0,nu.checkDataTypes)(c,r,o.opts.strictNumbers,nu.DataType.Wrong)}`}return B.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,B._)`!${c}(${r})`}return B.nil}}subschema(e,r){let n=(0,Nh.getSubschema)(this.it,e);(0,Nh.extendSubschemaData)(n,this.it,e),(0,Nh.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return ED(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Fr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Fr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,B.Name)),!0}};_n.KeywordCxt=su;function Wk(t,e,r,n){let s=new su(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Pi.funcKeywordCode)(s,r):"macro"in r?(0,Pi.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Pi.funcKeywordCode)(s,r)}var LD=/^\/(?:[^~]|~0|~1)*$/,FD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Gk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!LD.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=FD.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(o=r[e-d],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,B._)`${o}${(0,B.getProperty)((0,Fr.unescapeJsonPointer)(u))}`,i=(0,B._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}_n.getData=Gk});var ou=D(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var jh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};zh.default=jh});var Ci=D(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var Lh=$i(),Fh=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Lh.resolveUrl)(e,r,n),this.missingSchema=(0,Lh.normalizeId)((0,Lh.getFullPath)(e,this.missingRef))}};Uh.default=Fh});var au=D(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;var lr=re(),UD=ou(),ls=Lr(),dr=$i(),Kk=me(),HD=Ri(),io=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,dr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Yt.SchemaEnv=io;function Zh(t){let e=Jk.call(this,t);if(e)return e;let r=(0,dr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new lr.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:UD.default,code:(0,lr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ls.default.data,parentData:ls.default.parentData,parentDataProperty:ls.default.parentDataProperty,dataNames:[ls.default.data],dataPathArr:[lr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,lr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:lr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,lr._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,HD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(ls.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${ls.default.self}`,`${ls.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:h}=u;f.evaluated={props:m instanceof lr.Name?void 0:m,items:h instanceof lr.Name?void 0:h,dynamicProps:m instanceof lr.Name,dynamicItems:h instanceof lr.Name},f.source&&(f.source.evaluated=(0,lr.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Yt.compileSchema=Zh;function ZD(t,e,r){var n;r=(0,dr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=VD.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new io({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=BD.call(this,o)}Yt.resolveRef=ZD;function BD(t){return(0,dr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Zh.call(this,t)}function Jk(t){for(let e of this._compilations)if(qD(e,t))return e}Yt.getCompilingSchema=Jk;function qD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function VD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||iu.call(this,t,e)}function iu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,dr._getFullPath)(this.opts.uriResolver,r),s=(0,dr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Hh.call(this,r,t);let o=(0,dr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=iu.call(this,t,i);return typeof a?.schema!="object"?void 0:Hh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Zh.call(this,i),o===(0,dr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,dr.resolveUrl)(this.opts.uriResolver,s,u)),new io({schema:a,schemaId:c,root:t,baseId:s})}return Hh.call(this,r,i)}}Yt.resolveSchema=iu;var WD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Hh(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Kk.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!WD.has(a)&&u&&(e=(0,dr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Kk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,dr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=iu.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new io({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Yk=D((ZV,GD)=>{GD.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 qh=D((BV,t0)=>{"use strict";var KD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Qk=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Bh(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var JD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Xk(t){return t.length=0,!0}function YD(t,e,r){if(t.length){let n=Bh(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function XD(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=YD;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=Xk}else{s.push(u);continue}}return s.length&&(a===Xk?r.zone=s.join(""):i?n.push(s.join("")):n.push(Bh(s))),r.address=n.join(""),r}function e0(t){if(QD(t,":")<2)return{host:t,isIPV6:!1};let e=XD(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function QD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function eM(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function tM(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function rM(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Qk(r)){let n=e0(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}t0.exports={nonSimpleDomain:JD,recomposeAuthority:rM,normalizeComponentEncoding:tM,removeDotSegments:eM,isIPv4:Qk,isUUID:KD,normalizeIPv6:e0,stringArrayToHexStripped:Bh}});var i0=D((qV,o0)=>{"use strict";var{isUUID:nM}=qh(),sM=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,oM=["http","https","ws","wss","urn","urn:uuid"];function iM(t){return oM.indexOf(t)!==-1}function Vh(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 r0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function n0(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 aM(t){return t.secure=Vh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function cM(t){if((t.port===(Vh(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function uM(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(sM);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=Wh(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function lM(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=Wh(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function dM(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!nM(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function pM(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var s0={scheme:"http",domainHost:!0,parse:r0,serialize:n0},mM={scheme:"https",domainHost:s0.domainHost,parse:r0,serialize:n0},cu={scheme:"ws",domainHost:!0,parse:aM,serialize:cM},fM={scheme:"wss",domainHost:cu.domainHost,parse:cu.parse,serialize:cu.serialize},hM={scheme:"urn",parse:uM,serialize:lM,skipNormalize:!0},gM={scheme:"urn:uuid",parse:dM,serialize:pM,skipNormalize:!0},uu={http:s0,https:mM,ws:cu,wss:fM,urn:hM,"urn:uuid":gM};Object.setPrototypeOf(uu,null);function Wh(t){return t&&(uu[t]||uu[t.toLowerCase()])||void 0}o0.exports={wsIsSecure:Vh,SCHEMES:uu,isValidSchemeName:iM,getSchemeHandler:Wh}});var u0=D((VV,du)=>{"use strict";var{normalizeIPv6:yM,removeDotSegments:Oi,recomposeAuthority:_M,normalizeComponentEncoding:lu,isIPv4:xM,nonSimpleDomain:vM}=qh(),{SCHEMES:bM,getSchemeHandler:a0}=i0();function SM(t,e){return typeof t=="string"?t=Tr(Ur(t,e),e):typeof t=="object"&&(t=Ur(Tr(t,e),e)),t}function kM(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=c0(Ur(t,n),Ur(e,n),n,!0);return n.skipEscape=!0,Tr(s,n)}function c0(t,e,r,n){let s={};return n||(t=Ur(Tr(t,r),r),e=Ur(Tr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Oi(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Oi(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Oi(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Oi(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function wM(t,e,r){return typeof t=="string"?(t=unescape(t),t=Tr(lu(Ur(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Tr(lu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Tr(lu(Ur(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Tr(lu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Tr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],o=a0(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=_M(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Oi(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var EM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ur(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(EM);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(xM(n.host)===!1){let c=yM(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=a0(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&vM(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Gh={SCHEMES:bM,normalize:SM,resolve:kM,resolveComponent:c0,equal:wM,serialize:Tr,parse:Ur};du.exports=Gh;du.exports.default=Gh;du.exports.fastUri=Gh});var d0=D(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var l0=u0();l0.code='require("ajv/dist/runtime/uri").default';Kh.default=l0});var x0=D(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.CodeGen=et.Name=et.nil=et.stringify=et.str=et._=et.KeywordCxt=void 0;var $M=Ri();Object.defineProperty(et,"KeywordCxt",{enumerable:!0,get:function(){return $M.KeywordCxt}});var ao=re();Object.defineProperty(et,"_",{enumerable:!0,get:function(){return ao._}});Object.defineProperty(et,"str",{enumerable:!0,get:function(){return ao.str}});Object.defineProperty(et,"stringify",{enumerable:!0,get:function(){return ao.stringify}});Object.defineProperty(et,"nil",{enumerable:!0,get:function(){return ao.nil}});Object.defineProperty(et,"Name",{enumerable:!0,get:function(){return ao.Name}});Object.defineProperty(et,"CodeGen",{enumerable:!0,get:function(){return ao.CodeGen}});var TM=ou(),g0=Ci(),PM=wh(),Ii=au(),RM=re(),Ai=$i(),pu=Ei(),Yh=me(),p0=Yk(),CM=d0(),y0=(t,e)=>new RegExp(t,e);y0.code="new RegExp";var OM=["removeAdditional","useDefaults","coerceTypes"],IM=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),AM={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."},NM={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},m0=200;function DM(t){var e,r,n,s,o,i,a,c,u,d,l,p,f,m,h,g,_,v,y,x,k,R,$,P,j;let T=t.strict,C=(e=t.code)===null||e===void 0?void 0:e.optimize,L=C===!0||C===void 0?1:C||0,X=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:y0,ae=(s=t.uriResolver)!==null&&s!==void 0?s:CM.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:T)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:T)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:T)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=t.strictTuples)!==null&&l!==void 0?l:T)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:T)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:L,regExp:X}:{optimize:L,regExp:X},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:m0,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:m0,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(R=t.validateSchema)!==null&&R!==void 0?R:!0,validateFormats:($=t.validateFormats)!==null&&$!==void 0?$:!0,unicodeRegExp:(P=t.unicodeRegExp)!==null&&P!==void 0?P:!0,int32range:(j=t.int32range)!==null&&j!==void 0?j:!0,uriResolver:ae}}var Ni=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,...DM(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new RM.ValueScope({scope:{},prefixes:IM,es5:r,lines:n}),this.logger=UM(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,PM.getRules)(),f0.call(this,AM,e,"NOT SUPPORTED"),f0.call(this,NM,e,"DEPRECATED","warn"),this._metaOpts=LM.call(this),e.formats&&jM.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&zM.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),MM.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=p0;n==="id"&&(s={...p0},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,l){await o.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof g0.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await o.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Ai.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=h0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Ii.SchemaEnv({schema:{},schemaId:n});if(r=Ii.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=h0.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Ai.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(ZM.call(this,n,r),!r)return(0,Yh.eachItem)(n,o=>Jh.call(this,o)),this;qM.call(this,r);let s={...r,type:(0,pu.getJSONTypes)(r.type),schemaType:(0,pu.getJSONTypes)(r.schemaType)};return(0,Yh.eachItem)(n,s.type.length===0?o=>Jh.call(this,o,s):o=>s.type.forEach(i=>Jh.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=_0(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Ai.normalizeId)(i||n);let u=Ai.getSchemaRefs.call(this,e,n);return c=new Ii.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&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):Ii.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Ii.compileSchema.call(this,e)}finally{this.opts=r}}};Ni.ValidationError=TM.default;Ni.MissingRefError=g0.default;et.default=Ni;function f0(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function h0(t){return t=(0,Ai.normalizeId)(t),this.schemas[t]||this.refs[t]}function MM(){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 jM(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function zM(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function LM(){let t={...this.opts};for(let e of OM)delete t[e];return t}var FM={log(){},warn(){},error(){}};function UM(t){if(t===!1)return FM;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 HM=/^[a-z_$][a-z0-9_$:-]*$/i;function ZM(t,e){let{RULES:r}=this;if((0,Yh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!HM.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Jh(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,pu.getJSONTypes)(e.type),schemaType:(0,pu.getJSONTypes)(e.schemaType)}};e.before?BM.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function BM(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function qM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=_0(e)),t.validateSchema=this.compile(e,!0))}var VM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _0(t){return{anyOf:[t,VM]}}});var v0=D(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var WM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xh.default=WM});var w0=D(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.callRef=ds.getValidate=void 0;var GM=Ci(),b0=Jt(),Tt=re(),co=Lr(),S0=au(),mu=me(),KM={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return l();let d=S0.resolveRef.call(c,u,s,r);if(d===void 0)throw new GM.default(n.opts.uriResolver,s,r);if(d instanceof S0.SchemaEnv)return p(d);return f(d);function l(){if(o===u)return fu(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return fu(t,(0,Tt._)`${m}.validate`,u,u.$async)}function p(m){let h=k0(t,m);fu(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Tt.stringify)(m)}:{ref:m}),g=e.name("valid"),_=t.subschema({schema:m,dataTypes:[],schemaPath:Tt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(_),t.ok(g)}}};function k0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Tt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ds.getValidate=k0;function fu(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?co.default.this:Tt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,Tt._)`await ${(0,b0.callValidateCode)(t,e,u)}`),f(e),i||s.assign(m,!0)},h=>{s.if((0,Tt._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),p(h),i||s.assign(m,!1)}),t.ok(m)}function l(){t.result((0,b0.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,Tt._)`${m}.errors`;s.assign(co.default.vErrors,(0,Tt._)`${co.default.vErrors} === null ? ${h} : ${co.default.vErrors}.concat(${h})`),s.assign(co.default.errors,(0,Tt._)`${co.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=mu.mergeEvaluated.props(s,g.props,o.props));else{let _=s.var("props",(0,Tt._)`${m}.evaluated.props`);o.props=mu.mergeEvaluated.props(s,_,o.props,Tt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=mu.mergeEvaluated.items(s,g.items,o.items));else{let _=s.var("items",(0,Tt._)`${m}.evaluated.items`);o.items=mu.mergeEvaluated.items(s,_,o.items,Tt.Name)}}}ds.callRef=fu;ds.default=KM});var E0=D(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});var JM=v0(),YM=w0(),XM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",JM.default,YM.default];Qh.default=XM});var $0=D(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});var hu=re(),xn=hu.operators,gu={maximum:{okStr:"<=",ok:xn.LTE,fail:xn.GT},minimum:{okStr:">=",ok:xn.GTE,fail:xn.LT},exclusiveMaximum:{okStr:"<",ok:xn.LT,fail:xn.GTE},exclusiveMinimum:{okStr:">",ok:xn.GT,fail:xn.LTE}},QM={message:({keyword:t,schemaCode:e})=>(0,hu.str)`must be ${gu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,hu._)`{comparison: ${gu[t].okStr}, limit: ${e}}`},ej={keyword:Object.keys(gu),type:"number",schemaType:"number",$data:!0,error:QM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,hu._)`${r} ${gu[e].fail} ${n} || isNaN(${r})`)}};eg.default=ej});var T0=D(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var Di=re(),tj={message:({schemaCode:t})=>(0,Di.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Di._)`{multipleOf: ${t}}`},rj={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:tj,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Di._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Di._)`${i} !== parseInt(${i})`;t.fail$data((0,Di._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};tg.default=rj});var R0=D(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});function P0(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}rg.default=P0;P0.code='require("ajv/dist/runtime/ucs2length").default'});var C0=D(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var ps=re(),nj=me(),sj=R0(),oj={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ps.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ps._)`{limit: ${t}}`},ij={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:oj,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ps.operators.GT:ps.operators.LT,i=s.opts.unicode===!1?(0,ps._)`${r}.length`:(0,ps._)`${(0,nj.useFunc)(t.gen,sj.default)}(${r})`;t.fail$data((0,ps._)`${i} ${o} ${n}`)}};ng.default=ij});var O0=D(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var aj=Jt(),cj=me(),uo=re(),uj={message:({schemaCode:t})=>(0,uo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,uo._)`{pattern: ${t}}`},lj={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:uj,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,uo._)`new RegExp`:(0,cj.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,uo._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,uo._)`!${d}`)}else{let c=(0,aj.usePattern)(t,s);t.fail$data((0,uo._)`!${c}.test(${r})`)}}};sg.default=lj});var I0=D(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});var Mi=re(),dj={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Mi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Mi._)`{limit: ${t}}`},pj={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:dj,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Mi.operators.GT:Mi.operators.LT;t.fail$data((0,Mi._)`Object.keys(${r}).length ${s} ${n}`)}};og.default=pj});var A0=D(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var ji=Jt(),zi=re(),mj=me(),fj={message:({params:{missingProperty:t}})=>(0,zi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,zi._)`{missingProperty: ${t}}`},hj={keyword:"required",type:"object",schemaType:"array",$data:!0,error:fj,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,mj.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(zi.nil,l);else for(let f of r)(0,ji.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,ji.checkMissingProp)(t,r,f)),(0,ji.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,ji.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,ji.propertyInData)(e,s,f,a.ownProperties)),e.if((0,zi.not)(m),()=>{t.error(),e.break()})},zi.nil)}}};ig.default=hj});var N0=D(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var Li=re(),gj={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Li.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Li._)`{limit: ${t}}`},yj={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:gj,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Li.operators.GT:Li.operators.LT;t.fail$data((0,Li._)`${r}.length ${s} ${n}`)}};ag.default=yj});var yu=D(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var D0=Ih();D0.code='require("ajv/dist/runtime/equal").default';cg.default=D0});var M0=D(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var ug=Ei(),tt=re(),_j=me(),xj=yu(),vj={message:({params:{i:t,j:e}})=>(0,tt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,tt._)`{i: ${t}, j: ${e}}`},bj={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:vj,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,ug.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,tt._)`${i} === false`),t.ok(c);function d(){let m=e.let("i",(0,tt._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,tt._)`${m} > 1`,()=>(l()?p:f)(m,h))}function l(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let g=e.name("item"),_=(0,ug.checkDataTypes)(u,g,a.opts.strictNumbers,ug.DataType.Wrong),v=e.const("indices",(0,tt._)`{}`);e.for((0,tt._)`;${m}--;`,()=>{e.let(g,(0,tt._)`${r}[${m}]`),e.if(_,(0,tt._)`continue`),u.length>1&&e.if((0,tt._)`typeof ${g} == "string"`,(0,tt._)`${g} += "_"`),e.if((0,tt._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,tt._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,tt._)`${v}[${g}] = ${m}`)})}function f(m,h){let g=(0,_j.useFunc)(e,xj.default),_=e.name("outer");e.label(_).for((0,tt._)`;${m}--;`,()=>e.for((0,tt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,tt._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};lg.default=bj});var j0=D(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var dg=re(),Sj=me(),kj=yu(),wj={message:"must be equal to constant",params:({schemaCode:t})=>(0,dg._)`{allowedValue: ${t}}`},Ej={keyword:"const",$data:!0,error:wj,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,dg._)`!${(0,Sj.useFunc)(e,kj.default)}(${r}, ${s})`):t.fail((0,dg._)`${o} !== ${r}`)}};pg.default=Ej});var z0=D(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var Fi=re(),$j=me(),Tj=yu(),Pj={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Fi._)`{allowedValues: ${t}}`},Rj={keyword:"enum",schemaType:"array",$data:!0,error:Pj,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,$j.useFunc)(e,Tj.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);d=(0,Fi.or)(...s.map((m,h)=>p(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,f=>e.if((0,Fi._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Fi._)`${u()}(${r}, ${f}[${m}])`:(0,Fi._)`${r} === ${h}`}}};mg.default=Rj});var L0=D(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Cj=$0(),Oj=T0(),Ij=C0(),Aj=O0(),Nj=I0(),Dj=A0(),Mj=N0(),jj=M0(),zj=j0(),Lj=z0(),Fj=[Cj.default,Oj.default,Ij.default,Aj.default,Nj.default,Dj.default,Mj.default,jj.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},zj.default,Lj.default];fg.default=Fj});var gg=D(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.validateAdditionalItems=void 0;var ms=re(),hg=me(),Uj={message:({params:{len:t}})=>(0,ms.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ms._)`{limit: ${t}}`},Hj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Uj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,hg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}F0(t,n)}};function F0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,ms._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ms._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,hg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,ms._)`${a} <= ${e.length}`);r.if((0,ms.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:hg.Type.Num},u),i.allErrors||r.if((0,ms.not)(u),()=>r.break())})}}Ui.validateAdditionalItems=F0;Ui.default=Hj});var yg=D(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.validateTuple=void 0;var U0=re(),_u=me(),Zj=Jt(),Bj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return H0(t,"additionalItems",e);r.items=!0,!(0,_u.alwaysValidSchema)(r,e)&&t.ok((0,Zj.validateArray)(t))}};function H0(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;d(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=_u.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,U0._)`${o}.length`);r.forEach((l,p)=>{(0,_u.alwaysValidSchema)(a,l)||(n.if((0,U0._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function d(l){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===l.minItems&&(m===l.maxItems||l[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,_u.checkStrictMode)(a,g,p.strictTuples)}}}Hi.validateTuple=H0;Hi.default=Bj});var Z0=D(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var qj=yg(),Vj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,qj.validateTuple)(t,"items")};_g.default=Vj});var q0=D(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var B0=re(),Wj=me(),Gj=Jt(),Kj=gg(),Jj={message:({params:{len:t}})=>(0,B0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,B0._)`{limit: ${t}}`},Yj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Jj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Wj.alwaysValidSchema)(n,e)&&(s?(0,Kj.validateAdditionalItems)(t,s):t.ok((0,Gj.validateArray)(t)))}};xg.default=Yj});var V0=D(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var Xt=re(),xu=me(),Xj={message:({params:{min:t,max:e}})=>e===void 0?(0,Xt.str)`must contain at least ${t} valid item(s)`:(0,Xt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Xt._)`{minContains: ${t}}`:(0,Xt._)`{minContains: ${t}, maxContains: ${e}}`},Qj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Xj,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,Xt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,xu.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,xu.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xu.alwaysValidSchema)(o,r)){let h=(0,Xt._)`${d} >= ${i}`;a!==void 0&&(h=(0,Xt._)`${h} && ${d} <= ${a}`),t.pass(h);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Xt._)`${s}.length > 0`,p)):(e.let(l,!1),p()),t.result(l,()=>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,d,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:xu.Type.Num,compositeRule:!0},h),g()})}function m(h){e.code((0,Xt._)`${h}++`),a===void 0?e.if((0,Xt._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Xt._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Xt._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};vg.default=Qj});var K0=D(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.validateSchemaDeps=Pr.validatePropertyDeps=Pr.error=void 0;var bg=re(),ez=me(),Zi=Jt();Pr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,bg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,bg._)`{property: ${t},
69
69
  missingProperty: ${n},
70
70
  depsCount: ${e},
71
- deps: ${r}}`};var Yj={keyword:"dependencies",type:"object",schemaType:"object",error:Pr.error,code(t){let[e,r]=Xj(t);V0(t,e),W0(t,r)}};function Xj({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function V0(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Hi.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,Hi.checkReportMissingProp)(t,u)}):(r.if((0,xg._)`${c} && (${(0,Hi.checkMissingProp)(t,a,o)})`),(0,Hi.reportMissingProp)(t,o),r.else())}}Pr.validatePropertyDeps=V0;function W0(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,Jj.alwaysValidSchema)(o,e[a])||(r.if((0,Hi.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Pr.validateSchemaDeps=W0;Pr.default=Yj});var J0=D(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var K0=re(),Qj=me(),ez={message:"property name must be valid",params:({params:t})=>(0,K0._)`{propertyName: ${t.propertyName}}`},tz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ez,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Qj.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,K0.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};vg.default=tz});var Sg=D(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var xu=Jt(),pr=re(),rz=Lr(),vu=me(),nz={message:"must NOT have additional properties",params:({params:t})=>(0,pr._)`{additionalProperty: ${t.additionalProperty}}`},sz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nz,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,vu.alwaysValidSchema)(i,r))return;let u=(0,xu.allSchemaProperties)(n.properties),d=(0,xu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,pr._)`${o} === ${rz.default.errors}`);function l(){e.forIn("key",s,g=>{!u.length&&!d.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let _;if(u.length>8){let v=(0,vu.schemaRefOrVal)(i,n.properties,"properties");_=(0,xu.isOwnProperty)(e,v,g)}else u.length?_=(0,pr.or)(...u.map(v=>(0,pr._)`${g} === ${v}`)):_=pr.nil;return d.length&&(_=(0,pr.or)(_,...d.map(v=>(0,pr._)`${(0,xu.usePattern)(t,v)}.test(${g})`))),(0,pr.not)(_)}function f(g){e.code((0,pr._)`delete ${s}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,vu.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(g,_,!1),e.if((0,pr.not)(_),()=>{t.reset(),f(g)})):(h(g,_),a||e.if((0,pr.not)(_),()=>e.break()))}}function h(g,_,v){let y={keyword:"additionalProperties",dataProp:g,dataPropType:vu.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};bg.default=sz});var Q0=D(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var oz=Pi(),Y0=Jt(),kg=me(),X0=Sg(),iz={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&X0.default.code(new oz.KeywordCxt(o,X0.default,"additionalProperties"));let i=(0,Y0.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=kg.mergeEvaluated.props(e,(0,kg.toHash)(i),o.props));let a=i.filter(l=>!(0,kg.alwaysValidSchema)(o,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,Y0.propertyInData)(e,s,l,o.opts.ownProperties)),d(l),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return o.opts.useDefaults&&!o.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};wg.default=iz});var nw=D(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var ew=Jt(),bu=re(),tw=me(),rw=me(),az={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,ew.allSchemaProperties)(r),c=a.filter(h=>(0,tw.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof bu.Name)&&(o.props=(0,rw.evaluatedPropsToName)(e,o.props));let{props:l}=o;p();function p(){for(let h of a)u&&f(h),o.allErrors?m(h):(e.var(d,!0),m(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,tw.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,g=>{e.if((0,bu._)`${(0,ew.usePattern)(t,h)}.test(${g})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:rw.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,bu._)`${l}[${g}]`,!0):!_&&!o.allErrors&&e.if((0,bu.not)(d),()=>e.break())})})}}};Eg.default=az});var sw=D($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var cz=me(),uz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,cz.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};$g.default=uz});var ow=D(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var lz=Jt(),dz={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lz.validateUnion,error:{message:"must match a schema in anyOf"}};Tg.default=dz});var iw=D(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var Su=re(),pz=me(),mz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Su._)`{passingSchemas: ${t.passing}}`},fz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:mz,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((d,l)=>{let p;(0,pz.alwaysValidSchema)(s,d)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,Su._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Su._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),p&&t.mergeEvaluated(p,Su.Name)})})}}};Pg.default=fz});var aw=D(Rg=>{"use strict";Object.defineProperty(Rg,"__esModule",{value:!0});var hz=me(),gz={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,hz.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Rg.default=gz});var lw=D(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var ku=re(),uw=me(),yz={message:({params:t})=>(0,ku.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ku._)`{failingKeyword: ${t.ifClause}}`},_z={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,uw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=cw(n,"then"),o=cw(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else s?e.if(a,u("then")):e.if((0,ku.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let p=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(p,i),l?e.assign(l,(0,ku._)`${d}`):t.setParams({ifClause:d})}}}};function cw(t,e){let r=t.schema[e];return r!==void 0&&!(0,uw.alwaysValidSchema)(t,r)}Cg.default=_z});var dw=D(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var xz=me(),vz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,xz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Og.default=vz});var pw=D(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var bz=fg(),Sz=H0(),kz=hg(),wz=B0(),Ez=q0(),$z=G0(),Tz=J0(),Pz=Sg(),Rz=Q0(),Cz=nw(),Oz=sw(),Iz=ow(),Az=iw(),Nz=aw(),Dz=lw(),Mz=dw();function jz(t=!1){let e=[Oz.default,Iz.default,Az.default,Nz.default,Dz.default,Mz.default,Tz.default,Pz.default,$z.default,Rz.default,Cz.default];return t?e.push(Sz.default,wz.default):e.push(bz.default,kz.default),e.push(Ez.default),e}Ig.default=jz});var mw=D(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var He=re(),zz={message:({schemaCode:t})=>(0,He.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,He._)`{format: ${t}}`},Lz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:zz,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;s?p():f();function p(){let m=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,He._)`${m}[${i}]`),g=r.let("fType"),_=r.let("format");r.if((0,He._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,He._)`${h}.type || "string"`).assign(_,(0,He._)`${h}.validate`),()=>r.assign(g,(0,He._)`"string"`).assign(_,h)),t.fail$data((0,He.or)(v(),y()));function v(){return c.strictSchema===!1?He.nil:(0,He._)`${i} && !${_}`}function y(){let x=d.$async?(0,He._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,He._)`${_}(${n})`,k=(0,He._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,He._)`${_} && ${_} !== true && ${g} === ${e} && !${k}`}}function f(){let m=l.formats[o];if(!m){v();return}if(m===!0)return;let[h,g,_]=y(m);h===e&&t.pass(x());function v(){if(c.strictSchema===!1){l.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function y(k){let R=k instanceof RegExp?(0,He.regexpCode)(k):c.code.formats?(0,He._)`${c.code.formats}${(0,He.getProperty)(o)}`:void 0,$=r.scopeValue("formats",{key:o,ref:k,code:R});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,He._)`${$}.validate`]:["string",k,$]}function x(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!d.$async)throw new Error("async format in sync schema");return(0,He._)`await ${_}(${n})`}return typeof g=="function"?(0,He._)`${_}(${n})`:(0,He._)`${_}.test(${n})`}}}};Ag.default=Lz});var fw=D(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var Fz=mw(),Uz=[Fz.default];Ng.default=Uz});var hw=D(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.contentVocabulary=lo.metadataVocabulary=void 0;lo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];lo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var yw=D(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var Hz=w0(),Zz=z0(),Bz=pw(),qz=fw(),gw=hw(),Vz=[Hz.default,Zz.default,(0,Bz.default)(),qz.default,gw.metadataVocabulary,gw.contentVocabulary];Dg.default=Vz});var xw=D(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.DiscrError=void 0;var _w;(function(t){t.Tag="tag",t.Mapping="mapping"})(_w||(wu.DiscrError=_w={}))});var bw=D(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var po=re(),Mg=xw(),vw=iu(),Wz=Ri(),Gz=me(),Kz={message:({params:{discrError:t,tagName:e}})=>t===Mg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,po._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Jz={keyword:"discriminator",type:"object",schemaType:"object",error:Kz,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,po._)`${r}${(0,po.getProperty)(a)}`);e.if((0,po._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Mg.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,po._)`${u} === ${m}`),e.assign(c,l(f[m]));e.else(),t.error(!1,{discrError:Mg.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,po.Name),m}function p(){var f;let m={},h=_(s),g=!0;for(let x=0;x<i.length;x++){let k=i[x];if(k?.$ref&&!(0,Gz.schemaHasRulesButRef)(k,o.self.RULES)){let $=k.$ref;if(k=vw.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,$),k instanceof vw.SchemaEnv&&(k=k.schema),k===void 0)throw new Wz.default(o.opts.uriResolver,o.baseId,$)}let R=(f=k?.properties)===null||f===void 0?void 0:f[a];if(typeof R!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||_(k)),v(R,x)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function v(x,k){if(x.const)y(x.const,k);else if(x.enum)for(let R of x.enum)y(R,k);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,k){if(typeof x!="string"||x in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[x]=k}}}};jg.default=Jz});var Sw=D((P6,Yz)=>{Yz.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 Lg=D((Re,zg)=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.MissingRefError=Re.ValidationError=Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=Re.Ajv=void 0;var Xz=_0(),Qz=yw(),eL=bw(),kw=Sw(),tL=["/properties"],Eu="http://json-schema.org/draft-07/schema",mo=class extends Xz.default{_addVocabularies(){super._addVocabularies(),Qz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(eL.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(kw,tL):kw;this.addMetaSchema(e,Eu,!1),this.refs["http://json-schema.org/schema"]=Eu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Eu)?Eu:void 0)}};Re.Ajv=mo;zg.exports=Re=mo;zg.exports.Ajv=mo;Object.defineProperty(Re,"__esModule",{value:!0});Re.default=mo;var rL=Pi();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return rL.KeywordCxt}});var fo=re();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return fo._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return fo.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return fo.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return fo.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return fo.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return fo.CodeGen}});var nL=su();Object.defineProperty(Re,"ValidationError",{enumerable:!0,get:function(){return nL.default}});var sL=Ri();Object.defineProperty(Re,"MissingRefError",{enumerable:!0,get:function(){return sL.default}})});var Ow=D(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.formatNames=Cr.fastFormats=Cr.fullFormats=void 0;function Rr(t,e){return{validate:t,compare:e}}Cr.fullFormats={date:Rr(Tw,Zg),time:Rr(Ug(!0),Bg),"date-time":Rr(ww(!0),Rw),"iso-time":Rr(Ug(),Pw),"iso-date-time":Rr(ww(),Cw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:lL,"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:yL,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:dL,int32:{type:"number",validate:fL},int64:{type:"number",validate:hL},float:{type:"number",validate:$w},double:{type:"number",validate:$w},password:!0,binary:!0};Cr.fastFormats={...Cr.fullFormats,date:Rr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Zg),time:Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bg),"date-time":Rr(/^\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,Rw),"iso-time":Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Pw),"iso-date-time":Rr(/^\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,Cw),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};Cr.formatNames=Object.keys(Cr.fullFormats);function oL(t){return t%4===0&&(t%100!==0||t%400===0)}var iL=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,aL=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Tw(t){let e=iL.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&oL(r)?29:aL[n])}function Zg(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Fg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Ug(t){return function(r){let n=Fg.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let l=o-d*c,p=s-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function Bg(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Pw(t,e){if(!(t&&e))return;let r=Fg.exec(t),n=Fg.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Hg=/t|\s/i;function ww(t){let e=Ug(t);return function(n){let s=n.split(Hg);return s.length===2&&Tw(s[0])&&e(s[1])}}function Rw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Cw(t,e){if(!(t&&e))return;let[r,n]=t.split(Hg),[s,o]=e.split(Hg),i=Zg(r,s);if(i!==void 0)return i||Bg(n,o)}var cL=/\/|:/,uL=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function lL(t){return cL.test(t)&&uL.test(t)}var Ew=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function dL(t){return Ew.lastIndex=0,Ew.test(t)}var pL=-(2**31),mL=2**31-1;function fL(t){return Number.isInteger(t)&&t<=mL&&t>=pL}function hL(t){return Number.isInteger(t)}function $w(){return!0}var gL=/[^\\]\\Z/;function yL(t){if(gL.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Iw=D(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.formatLimitDefinition=void 0;var _L=Lg(),mr=re(),vn=mr.operators,$u={formatMaximum:{okStr:"<=",ok:vn.LTE,fail:vn.GT},formatMinimum:{okStr:">=",ok:vn.GTE,fail:vn.LT},formatExclusiveMaximum:{okStr:"<",ok:vn.LT,fail:vn.GTE},formatExclusiveMinimum:{okStr:">",ok:vn.GT,fail:vn.LTE}},xL={message:({keyword:t,schemaCode:e})=>(0,mr.str)`should be ${$u[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,mr._)`{comparison: ${$u[t].okStr}, limit: ${e}}`};ho.formatLimitDefinition={keyword:Object.keys($u),type:"string",schemaType:"string",$data:!0,error:xL,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new _L.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,mr._)`${p}[${c.schemaCode}]`);t.fail$data((0,mr.or)((0,mr._)`typeof ${f} != "object"`,(0,mr._)`${f} instanceof RegExp`,(0,mr._)`typeof ${f}.compare != "function"`,l(f)))}function d(){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(`"${s}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,mr._)`${i.code.formats}${(0,mr.getProperty)(p)}`:void 0});t.fail$data(l(m))}function l(p){return(0,mr._)`${p}.compare(${r}, ${n}) ${$u[s].fail} 0`}},dependencies:["format"]};var vL=t=>(t.addKeyword(ho.formatLimitDefinition),t);ho.default=vL});var Mw=D((Zi,Dw)=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var go=Ow(),bL=Iw(),qg=re(),Aw=new qg.Name("fullFormats"),SL=new qg.Name("fastFormats"),Vg=(t,e={keywords:!0})=>{if(Array.isArray(e))return Nw(t,e,go.fullFormats,Aw),t;let[r,n]=e.mode==="fast"?[go.fastFormats,SL]:[go.fullFormats,Aw],s=e.formats||go.formatNames;return Nw(t,s,r,n),e.keywords&&(0,bL.default)(t),t};Vg.get=(t,e="full")=>{let n=(e==="fast"?go.fastFormats:go.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Nw(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,qg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Dw.exports=Zi=Vg;Object.defineProperty(Zi,"__esModule",{value:!0});Zi.default=Vg});function kL(){let t=new jw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zw.default)(t),t}var jw,zw,Tu,Lw=b(()=>{jw=Po(Lg(),1),zw=Po(Mw(),1);Tu=class{constructor(e){this._ajv=e??kL()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Pu,Fw=b(()=>{rs();Pu=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(d=>d.type==="tool_use");if(i){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==l.size||![...d].every(p=>l.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},mi,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Xs,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function Uw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Hw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Zw=b(()=>{});var Ru,Bw=b(()=>{YS();rs();Lw();ti();Fw();Zw();Ru=class extends qc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(pi.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Tu,this.setRequestHandler(af,n=>this._oninitialize(n)),this.setNotificationHandler(cf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(hf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=pi.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Pu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=JS(this._capabilities,e)}setRequestHandler(e,r){let s=un(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(qt(s)){let a=s;o=a._zod?.def?.value??a.value}else{let a=s;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let d=cn(Ys,c);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new H(V.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let m=cn(Vs,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new H(V.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=cn(Ac,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new H(V.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Hw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Uw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Jb.includes(r)?r:tf,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"},vc)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.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(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(s.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},gf,r):this.request({method:"sampling/createMessage",params:e},mi,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},Xs,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Xs,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new H(V.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof H?i:new H(V.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},yf,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Wg(t){return!!t&&typeof t=="object"&&Vw in t}function Ww(t){return t[Vw]?.complete}var Vw,qw,Gw=b(()=>{Vw=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(qw||(qw={}))});var Kw=b(()=>{});function EL(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"),!wL.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function $L(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Gg(t){let e=EL(t);return $L(t,e.warnings),e.isValid}var wL,Jw=b(()=>{wL=/^[A-Za-z0-9._-]{1,128}$/});var Cu,Yw=b(()=>{Cu=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}});var Kg=b(()=>{Ba();Ba()});function eE(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function tE(t){return"_def"in t||"_zod"in t||eE(t)}function Jg(t){return typeof t!="object"||t===null||tE(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(eE)}function Xw(t){if(t){if(Jg(t))return ts(t);if(!tE(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function PL(t){let e=un(t);return e?Object.entries(e).map(([r,n])=>{let s=bb(n),o=Sb(n);return{name:r,description:s,required:!o}}):[]}function bn(t){let r=un(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Qw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ou,TL,Bi,rE=b(()=>{Bw();ti();eh();rs();Gw();Kw();Jw();Yw();Kg();Ou=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ru(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Cu(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Ic)),this.server.assertCanSetRequestHandler(bn(Ys)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ic,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=Bs(r.inputSchema);return s?Yf(s,{strictUnions:!0,pipeStrategy:"input"}):TL})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Bs(r.outputSchema);s&&(n.outputSchema=Yf(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ys,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new H(V.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new H(V.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new H(V.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof H&&n.code===V.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=Bs(e.inputSchema)??e.inputSchema,i=await pc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=mc(a);throw new H(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new H(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=Bs(e.outputSchema),o=await pc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=mc(i);throw new H(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,d));let l=await n.taskStore.getTask(c);if(!l)throw new H(V.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(bn(Nc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Nc,async e=>{switch(e.params.ref.type){case"ref/prompt":return pS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return mS(e),this.handleResourceCompletion(e,e.params.ref);default:throw new H(V.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new H(V.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Bi;let o=un(n.argsSchema)?.[e.params.argument.name];if(!Wg(o))return Bi;let i=Ww(o);if(!i)return Bi;let a=await i(e.params.argument.value,e.params.context);return Qw(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Bi;throw new H(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Bi;let o=await s(e.params.argument.value,e.params.context);return Qw(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Gs)),this.server.assertCanSetRequestHandler(bn(Ks)),this.server.assertCanSetRequestHandler(bn(Cc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Gs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Ks,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Cc,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new H(V.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new H(V.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Js)),this.server.assertCanSetRequestHandler(bn(Oc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Js,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?PL(r.argsSchema):void 0}))})),this.server.setRequestHandler(Oc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new H(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=Bs(n.argsSchema),o=await pc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=mc(c);throw new H(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:ts(s),callback:o,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=ts(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,s&&Object.values(s).some(c=>{let u=c instanceof bt?c._def?.innerType:c;return Wg(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){Gg(e);let d={title:r,description:n,inputSchema:Xw(s),outputSchema:Xw(o),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Gg(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=ts(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=ts(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Jg(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Jg(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,o,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},TL={type:"object",properties:{}};Bi={completion:{values:[],hasMore:!1}}});function RL(t){return sS.parse(JSON.parse(t))}function nE(t){return JSON.stringify(t)+`
72
- `}var Iu,sE=b(()=>{rs();Iu=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
73
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),RL(r)}clear(){this._buffer=void 0}}});import oE from"node:process";var Au,iE=b(()=>{sE();Au=class{constructor(e=oE.stdin,r=oE.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Iu,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=nE(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var gE={};Le(gE,{PolyglotExecutor:()=>yo,buildScriptFilename:()=>mE,buildShellScriptContent:()=>hE,buildSpawnOptions:()=>fE});import{spawn as aE,execSync as CL,execFileSync as dE}from"node:child_process";import{mkdtempSync as OL,writeFileSync as cE,rmSync as uE,existsSync as lE}from"node:fs";import{join as Nu,resolve as pE}from"node:path";import{tmpdir as IL}from"node:os";function mE(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${AL[t]}`}function fE(t){return{windowsHide:t==="win32"}}function NL(t){return`'${t.replace(/'/g,"'\\''")}'`}function hE(t,e,r){return r==="win32"||!e?t:`export PATH=${NL(e)}
74
- ${t}`}function Yg(t){if(Qt&&t.pid)try{CL(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Qt,AL,DL,yo,Xg=b(()=>{"use strict";ba();Qt=process.platform==="win32",AL={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs"};DL=(()=>{if(Qt)return process.env.TEMP??process.env.TMP??IL();try{let t=dE(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:pE(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();yo=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??vs()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Qt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:r,code:n,timeout:s,background:o=!1}=e,i=OL(Nu(DL,".ctx-mode-"));try{let a=this.#a(i,n,r),c=d_(this.#n,r,a);if(c[0]==="__rust_compile_run__")return await this.#c(a,i,s);let u=r==="shell"?this.#s:i,d=await this.#i(c,u,i,s,o);if(!d.backgrounded)try{uE(i,{recursive:!0,force:!0})}catch{}return d}catch(a){try{uE(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:s,timeout:o}=e,i=pE(this.#s,r),a=this.#l(i,n,s);return this.execute({language:n,code:a,timeout:o})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
71
+ deps: ${r}}`};var tz={keyword:"dependencies",type:"object",schemaType:"object",error:Pr.error,code(t){let[e,r]=rz(t);W0(t,e),G0(t,r)}};function rz({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function W0(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Zi.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,Zi.checkReportMissingProp)(t,u)}):(r.if((0,bg._)`${c} && (${(0,Zi.checkMissingProp)(t,a,o)})`),(0,Zi.reportMissingProp)(t,o),r.else())}}Pr.validatePropertyDeps=W0;function G0(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,ez.alwaysValidSchema)(o,e[a])||(r.if((0,Zi.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Pr.validateSchemaDeps=G0;Pr.default=tz});var Y0=D(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var J0=re(),nz=me(),sz={message:"property name must be valid",params:({params:t})=>(0,J0._)`{propertyName: ${t.propertyName}}`},oz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:sz,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,nz.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,J0.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Sg.default=oz});var wg=D(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var vu=Jt(),pr=re(),iz=Lr(),bu=me(),az={message:"must NOT have additional properties",params:({params:t})=>(0,pr._)`{additionalProperty: ${t.additionalProperty}}`},cz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:az,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,bu.alwaysValidSchema)(i,r))return;let u=(0,vu.allSchemaProperties)(n.properties),d=(0,vu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,pr._)`${o} === ${iz.default.errors}`);function l(){e.forIn("key",s,g=>{!u.length&&!d.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let _;if(u.length>8){let v=(0,bu.schemaRefOrVal)(i,n.properties,"properties");_=(0,vu.isOwnProperty)(e,v,g)}else u.length?_=(0,pr.or)(...u.map(v=>(0,pr._)`${g} === ${v}`)):_=pr.nil;return d.length&&(_=(0,pr.or)(_,...d.map(v=>(0,pr._)`${(0,vu.usePattern)(t,v)}.test(${g})`))),(0,pr.not)(_)}function f(g){e.code((0,pr._)`delete ${s}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,bu.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(g,_,!1),e.if((0,pr.not)(_),()=>{t.reset(),f(g)})):(h(g,_),a||e.if((0,pr.not)(_),()=>e.break()))}}function h(g,_,v){let y={keyword:"additionalProperties",dataProp:g,dataPropType:bu.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};kg.default=cz});var ew=D($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var uz=Ri(),X0=Jt(),Eg=me(),Q0=wg(),lz={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Q0.default.code(new uz.KeywordCxt(o,Q0.default,"additionalProperties"));let i=(0,X0.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Eg.mergeEvaluated.props(e,(0,Eg.toHash)(i),o.props));let a=i.filter(l=>!(0,Eg.alwaysValidSchema)(o,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,X0.propertyInData)(e,s,l,o.opts.ownProperties)),d(l),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return o.opts.useDefaults&&!o.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};$g.default=lz});var sw=D(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var tw=Jt(),Su=re(),rw=me(),nw=me(),dz={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,tw.allSchemaProperties)(r),c=a.filter(h=>(0,rw.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof Su.Name)&&(o.props=(0,nw.evaluatedPropsToName)(e,o.props));let{props:l}=o;p();function p(){for(let h of a)u&&f(h),o.allErrors?m(h):(e.var(d,!0),m(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,rw.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,g=>{e.if((0,Su._)`${(0,tw.usePattern)(t,h)}.test(${g})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:nw.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,Su._)`${l}[${g}]`,!0):!_&&!o.allErrors&&e.if((0,Su.not)(d),()=>e.break())})})}}};Tg.default=dz});var ow=D(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var pz=me(),mz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,pz.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Pg.default=mz});var iw=D(Rg=>{"use strict";Object.defineProperty(Rg,"__esModule",{value:!0});var fz=Jt(),hz={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fz.validateUnion,error:{message:"must match a schema in anyOf"}};Rg.default=hz});var aw=D(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var ku=re(),gz=me(),yz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ku._)`{passingSchemas: ${t.passing}}`},_z={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yz,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((d,l)=>{let p;(0,gz.alwaysValidSchema)(s,d)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,ku._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ku._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),p&&t.mergeEvaluated(p,ku.Name)})})}}};Cg.default=_z});var cw=D(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var xz=me(),vz={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,xz.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Og.default=vz});var dw=D(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var wu=re(),lw=me(),bz={message:({params:t})=>(0,wu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,wu._)`{failingKeyword: ${t.ifClause}}`},Sz={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:bz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,lw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=uw(n,"then"),o=uw(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else s?e.if(a,u("then")):e.if((0,wu.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let p=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(p,i),l?e.assign(l,(0,wu._)`${d}`):t.setParams({ifClause:d})}}}};function uw(t,e){let r=t.schema[e];return r!==void 0&&!(0,lw.alwaysValidSchema)(t,r)}Ig.default=Sz});var pw=D(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var kz=me(),wz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,kz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ag.default=wz});var mw=D(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var Ez=gg(),$z=Z0(),Tz=yg(),Pz=q0(),Rz=V0(),Cz=K0(),Oz=Y0(),Iz=wg(),Az=ew(),Nz=sw(),Dz=ow(),Mz=iw(),jz=aw(),zz=cw(),Lz=dw(),Fz=pw();function Uz(t=!1){let e=[Dz.default,Mz.default,jz.default,zz.default,Lz.default,Fz.default,Oz.default,Iz.default,Cz.default,Az.default,Nz.default];return t?e.push($z.default,Pz.default):e.push(Ez.default,Tz.default),e.push(Rz.default),e}Ng.default=Uz});var fw=D(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var He=re(),Hz={message:({schemaCode:t})=>(0,He.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,He._)`{format: ${t}}`},Zz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Hz,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;s?p():f();function p(){let m=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,He._)`${m}[${i}]`),g=r.let("fType"),_=r.let("format");r.if((0,He._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,He._)`${h}.type || "string"`).assign(_,(0,He._)`${h}.validate`),()=>r.assign(g,(0,He._)`"string"`).assign(_,h)),t.fail$data((0,He.or)(v(),y()));function v(){return c.strictSchema===!1?He.nil:(0,He._)`${i} && !${_}`}function y(){let x=d.$async?(0,He._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,He._)`${_}(${n})`,k=(0,He._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,He._)`${_} && ${_} !== true && ${g} === ${e} && !${k}`}}function f(){let m=l.formats[o];if(!m){v();return}if(m===!0)return;let[h,g,_]=y(m);h===e&&t.pass(x());function v(){if(c.strictSchema===!1){l.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function y(k){let R=k instanceof RegExp?(0,He.regexpCode)(k):c.code.formats?(0,He._)`${c.code.formats}${(0,He.getProperty)(o)}`:void 0,$=r.scopeValue("formats",{key:o,ref:k,code:R});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,He._)`${$}.validate`]:["string",k,$]}function x(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!d.$async)throw new Error("async format in sync schema");return(0,He._)`await ${_}(${n})`}return typeof g=="function"?(0,He._)`${_}(${n})`:(0,He._)`${_}.test(${n})`}}}};Dg.default=Zz});var hw=D(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var Bz=fw(),qz=[Bz.default];Mg.default=qz});var gw=D(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.contentVocabulary=lo.metadataVocabulary=void 0;lo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];lo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var _w=D(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var Vz=E0(),Wz=L0(),Gz=mw(),Kz=hw(),yw=gw(),Jz=[Vz.default,Wz.default,(0,Gz.default)(),Kz.default,yw.metadataVocabulary,yw.contentVocabulary];jg.default=Jz});var vw=D(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.DiscrError=void 0;var xw;(function(t){t.Tag="tag",t.Mapping="mapping"})(xw||(Eu.DiscrError=xw={}))});var Sw=D(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});var po=re(),zg=vw(),bw=au(),Yz=Ci(),Xz=me(),Qz={message:({params:{discrError:t,tagName:e}})=>t===zg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,po._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},eL={keyword:"discriminator",type:"object",schemaType:"object",error:Qz,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,po._)`${r}${(0,po.getProperty)(a)}`);e.if((0,po._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:zg.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,po._)`${u} === ${m}`),e.assign(c,l(f[m]));e.else(),t.error(!1,{discrError:zg.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,po.Name),m}function p(){var f;let m={},h=_(s),g=!0;for(let x=0;x<i.length;x++){let k=i[x];if(k?.$ref&&!(0,Xz.schemaHasRulesButRef)(k,o.self.RULES)){let $=k.$ref;if(k=bw.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,$),k instanceof bw.SchemaEnv&&(k=k.schema),k===void 0)throw new Yz.default(o.opts.uriResolver,o.baseId,$)}let R=(f=k?.properties)===null||f===void 0?void 0:f[a];if(typeof R!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||_(k)),v(R,x)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function v(x,k){if(x.const)y(x.const,k);else if(x.enum)for(let R of x.enum)y(R,k);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,k){if(typeof x!="string"||x in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[x]=k}}}};Lg.default=eL});var kw=D((N6,tL)=>{tL.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 Ug=D((Re,Fg)=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.MissingRefError=Re.ValidationError=Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=Re.Ajv=void 0;var rL=x0(),nL=_w(),sL=Sw(),ww=kw(),oL=["/properties"],$u="http://json-schema.org/draft-07/schema",mo=class extends rL.default{_addVocabularies(){super._addVocabularies(),nL.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(sL.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ww,oL):ww;this.addMetaSchema(e,$u,!1),this.refs["http://json-schema.org/schema"]=$u}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema($u)?$u:void 0)}};Re.Ajv=mo;Fg.exports=Re=mo;Fg.exports.Ajv=mo;Object.defineProperty(Re,"__esModule",{value:!0});Re.default=mo;var iL=Ri();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return iL.KeywordCxt}});var fo=re();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return fo._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return fo.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return fo.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return fo.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return fo.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return fo.CodeGen}});var aL=ou();Object.defineProperty(Re,"ValidationError",{enumerable:!0,get:function(){return aL.default}});var cL=Ci();Object.defineProperty(Re,"MissingRefError",{enumerable:!0,get:function(){return cL.default}})});var Iw=D(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.formatNames=Cr.fastFormats=Cr.fullFormats=void 0;function Rr(t,e){return{validate:t,compare:e}}Cr.fullFormats={date:Rr(Pw,qg),time:Rr(Zg(!0),Vg),"date-time":Rr(Ew(!0),Cw),"iso-time":Rr(Zg(),Rw),"iso-date-time":Rr(Ew(),Ow),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:fL,"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:bL,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:hL,int32:{type:"number",validate:_L},int64:{type:"number",validate:xL},float:{type:"number",validate:Tw},double:{type:"number",validate:Tw},password:!0,binary:!0};Cr.fastFormats={...Cr.fullFormats,date:Rr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,qg),time:Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Vg),"date-time":Rr(/^\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,Cw),"iso-time":Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Rw),"iso-date-time":Rr(/^\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,Ow),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};Cr.formatNames=Object.keys(Cr.fullFormats);function uL(t){return t%4===0&&(t%100!==0||t%400===0)}var lL=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dL=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Pw(t){let e=lL.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&uL(r)?29:dL[n])}function qg(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Hg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Zg(t){return function(r){let n=Hg.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let l=o-d*c,p=s-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function Vg(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Rw(t,e){if(!(t&&e))return;let r=Hg.exec(t),n=Hg.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Bg=/t|\s/i;function Ew(t){let e=Zg(t);return function(n){let s=n.split(Bg);return s.length===2&&Pw(s[0])&&e(s[1])}}function Cw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Ow(t,e){if(!(t&&e))return;let[r,n]=t.split(Bg),[s,o]=e.split(Bg),i=qg(r,s);if(i!==void 0)return i||Vg(n,o)}var pL=/\/|:/,mL=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function fL(t){return pL.test(t)&&mL.test(t)}var $w=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function hL(t){return $w.lastIndex=0,$w.test(t)}var gL=-(2**31),yL=2**31-1;function _L(t){return Number.isInteger(t)&&t<=yL&&t>=gL}function xL(t){return Number.isInteger(t)}function Tw(){return!0}var vL=/[^\\]\\Z/;function bL(t){if(vL.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Aw=D(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.formatLimitDefinition=void 0;var SL=Ug(),mr=re(),vn=mr.operators,Tu={formatMaximum:{okStr:"<=",ok:vn.LTE,fail:vn.GT},formatMinimum:{okStr:">=",ok:vn.GTE,fail:vn.LT},formatExclusiveMaximum:{okStr:"<",ok:vn.LT,fail:vn.GTE},formatExclusiveMinimum:{okStr:">",ok:vn.GT,fail:vn.LTE}},kL={message:({keyword:t,schemaCode:e})=>(0,mr.str)`should be ${Tu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,mr._)`{comparison: ${Tu[t].okStr}, limit: ${e}}`};ho.formatLimitDefinition={keyword:Object.keys(Tu),type:"string",schemaType:"string",$data:!0,error:kL,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new SL.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,mr._)`${p}[${c.schemaCode}]`);t.fail$data((0,mr.or)((0,mr._)`typeof ${f} != "object"`,(0,mr._)`${f} instanceof RegExp`,(0,mr._)`typeof ${f}.compare != "function"`,l(f)))}function d(){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(`"${s}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,mr._)`${i.code.formats}${(0,mr.getProperty)(p)}`:void 0});t.fail$data(l(m))}function l(p){return(0,mr._)`${p}.compare(${r}, ${n}) ${Tu[s].fail} 0`}},dependencies:["format"]};var wL=t=>(t.addKeyword(ho.formatLimitDefinition),t);ho.default=wL});var jw=D((Bi,Mw)=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});var go=Iw(),EL=Aw(),Wg=re(),Nw=new Wg.Name("fullFormats"),$L=new Wg.Name("fastFormats"),Gg=(t,e={keywords:!0})=>{if(Array.isArray(e))return Dw(t,e,go.fullFormats,Nw),t;let[r,n]=e.mode==="fast"?[go.fastFormats,$L]:[go.fullFormats,Nw],s=e.formats||go.formatNames;return Dw(t,s,r,n),e.keywords&&(0,EL.default)(t),t};Gg.get=(t,e="full")=>{let n=(e==="fast"?go.fastFormats:go.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Dw(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Wg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Mw.exports=Bi=Gg;Object.defineProperty(Bi,"__esModule",{value:!0});Bi.default=Gg});function TL(){let t=new zw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Lw.default)(t),t}var zw,Lw,Pu,Fw=b(()=>{zw=Po(Ug(),1),Lw=Po(jw(),1);Pu=class{constructor(e){this._ajv=e??TL()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Ru,Uw=b(()=>{ns();Ru=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(d=>d.type==="tool_use");if(i){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==l.size||![...d].every(p=>l.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},fi,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Xs,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function Hw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Zw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Bw=b(()=>{});var Cu,qw=b(()=>{XS();ns();Fw();ri();Uw();Bw();Cu=class extends Vc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(mi.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Pu,this.setRequestHandler(uf,n=>this._oninitialize(n)),this.setNotificationHandler(lf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(yf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=mi.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ru(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=YS(this._capabilities,e)}setRequestHandler(e,r){let s=un(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(qt(s)){let a=s;o=a._zod?.def?.value??a.value}else{let a=s;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let d=cn(Ys,c);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new H(V.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let m=cn(Vs,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new H(V.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=cn(Nc,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new H(V.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Zw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Hw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Yb.includes(r)?r:nf,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"},bc)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.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(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(s.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},_f,r):this.request({method:"sampling/createMessage",params:e},fi,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},Xs,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Xs,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new H(V.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof H?i:new H(V.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},xf,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Kg(t){return!!t&&typeof t=="object"&&Ww in t}function Gw(t){return t[Ww]?.complete}var Ww,Vw,Kw=b(()=>{Ww=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Vw||(Vw={}))});var Jw=b(()=>{});function RL(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"),!PL.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function CL(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Jg(t){let e=RL(t);return CL(t,e.warnings),e.isValid}var PL,Yw=b(()=>{PL=/^[A-Za-z0-9._-]{1,128}$/});var Ou,Xw=b(()=>{Ou=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}});var Yg=b(()=>{qa();qa()});function tE(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function rE(t){return"_def"in t||"_zod"in t||tE(t)}function Xg(t){return typeof t!="object"||t===null||rE(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(tE)}function Qw(t){if(t){if(Xg(t))return rs(t);if(!rE(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function IL(t){let e=un(t);return e?Object.entries(e).map(([r,n])=>{let s=Sb(n),o=kb(n);return{name:r,description:s,required:!o}}):[]}function bn(t){let r=un(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=hc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function eE(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Iu,OL,qi,nE=b(()=>{qw();ri();rh();ns();Kw();Jw();Yw();Xw();Yg();Iu=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Cu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ou(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Ac)),this.server.assertCanSetRequestHandler(bn(Ys)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ac,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=Bs(r.inputSchema);return s?Qf(s,{strictUnions:!0,pipeStrategy:"input"}):OL})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Bs(r.outputSchema);s&&(n.outputSchema=Qf(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ys,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new H(V.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new H(V.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new H(V.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof H&&n.code===V.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=Bs(e.inputSchema)??e.inputSchema,i=await mc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=fc(a);throw new H(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new H(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=Bs(e.outputSchema),o=await mc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=fc(i);throw new H(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,d));let l=await n.taskStore.getTask(c);if(!l)throw new H(V.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(bn(Dc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Dc,async e=>{switch(e.params.ref.type){case"ref/prompt":return mS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return fS(e),this.handleResourceCompletion(e,e.params.ref);default:throw new H(V.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new H(V.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return qi;let o=un(n.argsSchema)?.[e.params.argument.name];if(!Kg(o))return qi;let i=Gw(o);if(!i)return qi;let a=await i(e.params.argument.value,e.params.context);return eE(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return qi;throw new H(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return qi;let o=await s(e.params.argument.value,e.params.context);return eE(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Gs)),this.server.assertCanSetRequestHandler(bn(Ks)),this.server.assertCanSetRequestHandler(bn(Oc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Gs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Ks,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Oc,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new H(V.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new H(V.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Js)),this.server.assertCanSetRequestHandler(bn(Ic)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Js,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?IL(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ic,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new H(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=Bs(n.argsSchema),o=await mc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=fc(c);throw new H(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:rs(s),callback:o,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=rs(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,s&&Object.values(s).some(c=>{let u=c instanceof bt?c._def?.innerType:c;return Kg(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){Jg(e);let d={title:r,description:n,inputSchema:Qw(s),outputSchema:Qw(o),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Jg(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=rs(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=rs(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Xg(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Xg(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,o,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},OL={type:"object",properties:{}};qi={completion:{values:[],hasMore:!1}}});function AL(t){return oS.parse(JSON.parse(t))}function sE(t){return JSON.stringify(t)+`
72
+ `}var Au,oE=b(()=>{ns();Au=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
73
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),AL(r)}clear(){this._buffer=void 0}}});import iE from"node:process";var Nu,aE=b(()=>{oE();Nu=class{constructor(e=iE.stdin,r=iE.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Au,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=sE(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var yE={};Le(yE,{PolyglotExecutor:()=>yo,buildScriptFilename:()=>fE,buildShellScriptContent:()=>gE,buildSpawnOptions:()=>hE});import{spawn as cE,execSync as NL,execFileSync as pE}from"node:child_process";import{mkdtempSync as DL,writeFileSync as uE,rmSync as lE,existsSync as dE}from"node:fs";import{join as Du,resolve as mE}from"node:path";import{tmpdir as ML}from"node:os";function fE(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${jL[t]}`}function hE(t){return{windowsHide:t==="win32"}}function zL(t){return`'${t.replace(/'/g,"'\\''")}'`}function gE(t,e,r){return r==="win32"||!e?t:`export PATH=${zL(e)}
74
+ ${t}`}function Qg(t){if(Qt&&t.pid)try{NL(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Qt,jL,LL,yo,ey=b(()=>{"use strict";Sa();Qt=process.platform==="win32",jL={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs"};LL=(()=>{if(Qt)return process.env.TEMP??process.env.TMP??ML();try{let t=pE(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:mE(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();yo=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??bs()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Qt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:r,code:n,timeout:s,background:o=!1}=e,i=DL(Du(LL,".ctx-mode-"));try{let a=this.#a(i,n,r),c=m_(this.#n,r,a);if(c[0]==="__rust_compile_run__")return await this.#c(a,i,s);let u=r==="shell"?this.#s:i,d=await this.#i(c,u,i,s,o);if(!d.backgrounded)try{lE(i,{recursive:!0,force:!0})}catch{}return d}catch(a){try{lE(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:s,timeout:o}=e,i=mE(this.#s,r),a=this.#l(i,n,s);return this.execute({language:n,code:a,timeout:o})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
75
75
 
76
76
  import "fmt"
77
77
 
@@ -79,12 +79,12 @@ func main() {
79
79
  ${r}
80
80
  }
81
81
  `),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
82
- ${r}`),n==="elixir"&&lE(Nu(this.#s,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(Nu(this.#s,"_build/dev/lib"))}, "*/ebin"))
82
+ ${r}`),n==="elixir"&&dE(Du(this.#s,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(Du(this.#s,"_build/dev/lib"))}, "*/ebin"))
83
83
  |> Enum.each(&Code.prepend_path/1)
84
84
 
85
- ${r}`);let s=Nu(e,mE(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?cE(s,hE(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):cE(s,r,"utf-8"),s}async#c(e,r,n){let s=Qt?".exe":"",o=e.replace(/\.rs$/,"")+s;try{dE("rustc",[e,"-o",o],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
86
- ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([o],r,r,n)}async#i(e,r,n,s,o=!1){return new Promise(i=>{let a=Qt&&["tsx","ts-node","elixir","bun"].includes(e[0]),c=e[0],u;Qt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Qt?e.slice(1).map(y=>y.replace(/\\/g,"/")):e.slice(1);let d={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!Qt,...fE(process.platform)},l;if(a){let y=[c,...u].map(x=>/\s/.test(x)?JSON.stringify(x):x).join(" ");l=aE(y,[],{...d,shell:!0})}else l=aE(c,u,{...d,shell:!1});let p=!1,f=!1,m=s===void 0?void 0:setTimeout(()=>{if(p=!0,o){f=!0,l.pid&&this.#o.add(l.pid),l.unref(),l.stdout.destroy(),l.stderr.destroy();let y=Buffer.concat(h).toString("utf-8"),x=Buffer.concat(g).toString("utf-8");i({stdout:y,stderr:x,exitCode:0,timedOut:!0,backgrounded:!0})}else Yg(l)},s),h=[],g=[],_=0,v=!1;l.stdout.on("data",y=>{_+=y.length,_<=this.#e?h.push(y):v||(v=!0,Yg(l))}),l.stderr.on("data",y=>{_+=y.length,_<=this.#e?g.push(y):v||(v=!0,Yg(l))}),l.on("close",y=>{if(clearTimeout(m),f)return;let x=Buffer.concat(h).toString("utf-8"),k=Buffer.concat(g).toString("utf-8");v&&(k+=`
87
- [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:x,stderr:k,exitCode:p?1:y??1,timedOut:p})}),l.on("error",y=>{clearTimeout(m),!f&&i({stdout:"",stderr:y.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","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"]),s={};for(let[o,i]of Object.entries(process.env))i!==void 0&&!n.has(o)&&!o.startsWith("BASH_FUNC_")&&(s[o]=i);if(s.TMPDIR=e,s.HOME=r,s.LANG="en_US.UTF-8",s.PYTHONDONTWRITEBYTECODE="1",s.PYTHONUNBUFFERED="1",s.PYTHONUTF8="1",s.NO_COLOR="1",Qt&&!s.PATH&&s.Path&&(s.PATH=s.Path,delete s.Path),s.PATH||(s.PATH=Qt?"":"/usr/local/bin:/usr/bin:/bin"),Qt){s.MSYS_NO_PATHCONV="1",s.MSYS2_ARG_CONV_EXCL="*";let o="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";s.PATH.includes(o)||(s.PATH=`${o};${i};${s.PATH}`)}if(!s.SSL_CERT_FILE){let o=Qt?[]:["/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 o)if(lE(i)){s.SSL_CERT_FILE=i;break}}return s}#l(e,r,n){let s=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${s};
85
+ ${r}`);let s=Du(e,fE(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?uE(s,gE(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):uE(s,r,"utf-8"),s}async#c(e,r,n){let s=Qt?".exe":"",o=e.replace(/\.rs$/,"")+s;try{pE("rustc",[e,"-o",o],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
86
+ ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([o],r,r,n)}async#i(e,r,n,s,o=!1){return new Promise(i=>{let a=Qt&&["tsx","ts-node","elixir","bun"].includes(e[0]),c=e[0],u;Qt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Qt?e.slice(1).map(y=>y.replace(/\\/g,"/")):e.slice(1);let d={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!Qt,...hE(process.platform)},l;if(a){let y=[c,...u].map(x=>/\s/.test(x)?JSON.stringify(x):x).join(" ");l=cE(y,[],{...d,shell:!0})}else l=cE(c,u,{...d,shell:!1});let p=!1,f=!1,m=s===void 0?void 0:setTimeout(()=>{if(p=!0,o){f=!0,l.pid&&this.#o.add(l.pid),l.unref(),l.stdout.destroy(),l.stderr.destroy();let y=Buffer.concat(h).toString("utf-8"),x=Buffer.concat(g).toString("utf-8");i({stdout:y,stderr:x,exitCode:0,timedOut:!0,backgrounded:!0})}else Qg(l)},s),h=[],g=[],_=0,v=!1;l.stdout.on("data",y=>{_+=y.length,_<=this.#e?h.push(y):v||(v=!0,Qg(l))}),l.stderr.on("data",y=>{_+=y.length,_<=this.#e?g.push(y):v||(v=!0,Qg(l))}),l.on("close",y=>{if(clearTimeout(m),f)return;let x=Buffer.concat(h).toString("utf-8"),k=Buffer.concat(g).toString("utf-8");v&&(k+=`
87
+ [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:x,stderr:k,exitCode:p?1:y??1,timedOut:p})}),l.on("error",y=>{clearTimeout(m),!f&&i({stdout:"",stderr:y.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","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"]),s={};for(let[o,i]of Object.entries(process.env))i!==void 0&&!n.has(o)&&!o.startsWith("BASH_FUNC_")&&(s[o]=i);if(s.TMPDIR=e,s.HOME=r,s.LANG="en_US.UTF-8",s.PYTHONDONTWRITEBYTECODE="1",s.PYTHONUNBUFFERED="1",s.PYTHONUTF8="1",s.NO_COLOR="1",Qt&&!s.PATH&&s.Path&&(s.PATH=s.Path,delete s.Path),s.PATH||(s.PATH=Qt?"":"/usr/local/bin:/usr/bin:/bin"),Qt){s.MSYS_NO_PATHCONV="1",s.MSYS2_ARG_CONV_EXCL="*";let o="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";s.PATH.includes(o)||(s.PATH=`${o};${i};${s.PATH}`)}if(!s.SSL_CERT_FILE){let o=Qt?[]:["/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 o)if(dE(i)){s.SSL_CERT_FILE=i;break}}return s}#l(e,r,n){let s=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${s};
88
88
  const file_path = FILE_CONTENT_PATH;
89
89
  const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
90
90
  ${n}`;case"python":return`FILE_CONTENT_PATH = ${s}
@@ -139,7 +139,7 @@ FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
139
139
  ${n}`;case"elixir":return`file_content_path = ${s}
140
140
  file_path = file_content_path
141
141
  file_content = File.read!(file_content_path)
142
- ${n}`}}}});import{cpus as ML}from"node:os";async function Qg(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:s}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let o=Math.max(1,r),i=n?Math.max(1,ML().length):o,a=Math.min(o,i,t.length),c=a<o,u=new Array(t.length),d=0;async function l(){for(;;){let f=d++;if(f>=t.length)return;try{let m=await t[f].run();u[f]={status:"fulfilled",value:m}}catch(m){u[f]={status:"rejected",reason:m}}s?.(f,u[f])}}let p=[];for(let f=0;f<a;f++)p.push(l());return await Promise.allSettled(p),{settled:u,effectiveConcurrency:a,capped:c}}var yE=b(()=>{"use strict"});var bE={};Le(bE,{BunSQLiteAdapter:()=>Du,NodeSQLiteAdapter:()=>Mu,SQLiteBase:()=>Vi,applyWALPragmas:()=>xo,cleanOrphanedWALFiles:()=>vo,closeDB:()=>bo,defaultDBPath:()=>ty,deleteDBFiles:()=>ju,isSQLiteCorruptionError:()=>zu,loadDatabase:()=>Pt,nodeSqliteHasFts5:()=>xE,renameCorruptDB:()=>vE,withRetry:()=>Sn});import{createRequire as jL}from"node:module";import{existsSync as zL,unlinkSync as _E,renameSync as LL}from"node:fs";import{tmpdir as FL}from"node:os";import{join as UL}from"node:path";function xE(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 Pt(){if(!_o){let t=jL(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;_o=function(n,s){let o=new e(n,{readonly:s?.readonly,create:!0}),i=new Du(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}}else if(process.platform==="linux"){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&xE(e)?_o=function(n,s){let o=new e(n,{readOnly:s?.readonly??!1});return new Mu(o)}:_o=t("better-sqlite3")}else _o=t("better-sqlite3")}return _o}function xo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function vo(t){if(!zL(t))for(let e of["-wal","-shm"])try{_E(t+e)}catch{}}function ju(t){for(let e of["","-wal","-shm"])try{_E(t+e)}catch{}}function bo(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ty(t="context-mode"){return UL(FL(),`${t}-${process.pid}.db`)}function Sn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(s){let o=s instanceof Error?s.message:String(s);if(!o.includes("SQLITE_BUSY")&&!o.includes("database is locked"))throw s;if(r=s instanceof Error?s:new Error(o),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function zu(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function vE(t){let e=Date.now();for(let r of["","-wal","-shm"])try{LL(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Du,Mu,_o,qi,ey,Vi,ms=b(()=>{"use strict";Du=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let s=Object.values(n[0]);return s.length===1?s[0]:n[0]}exec(e){let r="",n=null;for(let o=0;o<e.length;o++){let i=e[o];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let s=r.trim();return s&&this.#e.prepare(s).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let s=r.get(...n);return s===null?void 0:s},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},Mu=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let s=Object.values(n[0]);return s.length===1?s[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},_o=null;qi=Symbol.for("__context_mode_live_dbs__"),ey=(()=>{let t=globalThis;return t[qi]||(t[qi]=new Set,process.on("exit",()=>{for(let e of t[qi])bo(e);t[qi].clear()})),t[qi]})(),Vi=class{#e;#t;constructor(e){let r=Pt();this.#e=e,vo(e);let n;try{n=new r(e,{timeout:3e4}),xo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(zu(o)){vE(e),vo(e);try{n=new r(e,{timeout:3e4}),xo(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#t=n,ey.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){ey.delete(this.#t),bo(this.#t)}withRetry(e){return Sn(e)}cleanup(){ey.delete(this.#t),bo(this.#t),ju(this.#e)}}});import{readFileSync as SE,readdirSync as PE,unlinkSync as ny,existsSync as ry,statSync as Lu,openSync as kE,fstatSync as wE,closeSync as EE}from"node:fs";import{createHash as $E}from"node:crypto";import{tmpdir as RE}from"node:os";import{join as sy}from"node:path";function CE(t){let e=new Set,r=[];for(let n of t){let s=n.toLowerCase();e.has(s)||(e.add(s),r.push(n))}return r}function HL(t,e="AND"){let r=CE(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(o=>o.length>0&&!["AND","OR","NOT","NEAR"].includes(o.toUpperCase())));if(r.length===0)return'""';let n=r.filter(o=>!So.has(o.toLowerCase()));return(n.length>0?n:r).map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function ZL(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=CE(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let s=n.filter(i=>!So.has(i.toLowerCase()));return(s.length>0?s:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function BL(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,s)=>s);for(let n=1;n<=t.length;n++){let s=[n];for(let o=1;o<=e.length;o++)s[o]=t[n-1]===e[o-1]?r[o-1]:1+Math.min(r[o],s[o-1],r[o-1]);r=s}return r[e.length]}function qL(t){return t<=4?1:t<=12?2:3}function oy(){let t=RE(),e=0;try{let r=PE(t);for(let n of r){let s=n.match(/^context-mode-(\d+)\.db$/);if(!s)continue;let o=parseInt(s[1],10);if(o!==process.pid)try{process.kill(o,0)}catch{let i=sy(t,n);for(let a of["","-wal","-shm"])try{ny(i+a)}catch{}e++}}}catch{}return e}function iy(t,e){let r=0;try{if(!ry(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=PE(t).filter(o=>o.endsWith(".db"));for(let o of s)try{let i=sy(t,o),c=Lu(i).mtimeMs<n;if(!c){let u=i+"-wal";if(ry(u))try{let d=Lu(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{ny(i+u)}catch{}r++}}catch{}}catch{}return r}function VL(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function WL(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,s=Math.min(t.length,e.length)-1;for(let o=0;o<s;o++){let i=t[o],a=t[o+1],c=e[o].length,u=0;for(let d of i){let l=d+c,p=l+r;for(;u<a.length&&a[u]<l;)u++;u<a.length&&a[u]<=p&&(n++,u++)}}return n}function GL(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(s=>[...s].sort((o,i)=>o-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let s=1/0,o=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<s&&(s=u,i=c),u>o&&(o=u)}let a=o-s;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var So,TE,Fu,OE=b(()=>{"use strict";ms();So=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"]);TE=4096;Fu=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#x;#v;#b;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=Pt();this.#t=e??sy(RE(),`context-mode-${process.pid}.db`),vo(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),xo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(zu(o)){ju(this.#t),vo(this.#t);try{n=new r(this.#t,{timeout:3e4}),xo(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#e=n,this.#H(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{ny(this.#t+e)}catch{}}#H(){this.#e.exec(`
142
+ ${n}`}}}});import{cpus as FL}from"node:os";async function ty(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:s}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let o=Math.max(1,r),i=n?Math.max(1,FL().length):o,a=Math.min(o,i,t.length),c=a<o,u=new Array(t.length),d=0;async function l(){for(;;){let f=d++;if(f>=t.length)return;try{let m=await t[f].run();u[f]={status:"fulfilled",value:m}}catch(m){u[f]={status:"rejected",reason:m}}s?.(f,u[f])}}let p=[];for(let f=0;f<a;f++)p.push(l());return await Promise.allSettled(p),{settled:u,effectiveConcurrency:a,capped:c}}var _E=b(()=>{"use strict"});var SE={};Le(SE,{BunSQLiteAdapter:()=>Mu,NodeSQLiteAdapter:()=>ju,SQLiteBase:()=>Wi,applyWALPragmas:()=>xo,cleanOrphanedWALFiles:()=>vo,closeDB:()=>bo,defaultDBPath:()=>ny,deleteDBFiles:()=>zu,isSQLiteCorruptionError:()=>Lu,loadDatabase:()=>Pt,nodeSqliteHasFts5:()=>vE,renameCorruptDB:()=>bE,withRetry:()=>Sn});import{createRequire as UL}from"node:module";import{existsSync as HL,unlinkSync as xE,renameSync as ZL}from"node:fs";import{tmpdir as BL}from"node:os";import{join as qL}from"node:path";function vE(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 Pt(){if(!_o){let t=UL(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;_o=function(n,s){let o=new e(n,{readonly:s?.readonly,create:!0}),i=new Mu(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}}else if(process.platform==="linux"){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&vE(e)?_o=function(n,s){let o=new e(n,{readOnly:s?.readonly??!1});return new ju(o)}:_o=t("better-sqlite3")}else _o=t("better-sqlite3")}return _o}function xo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function vo(t){if(!HL(t))for(let e of["-wal","-shm"])try{xE(t+e)}catch{}}function zu(t){for(let e of["","-wal","-shm"])try{xE(t+e)}catch{}}function bo(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ny(t="context-mode"){return qL(BL(),`${t}-${process.pid}.db`)}function Sn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(s){let o=s instanceof Error?s.message:String(s);if(!o.includes("SQLITE_BUSY")&&!o.includes("database is locked"))throw s;if(r=s instanceof Error?s:new Error(o),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function Lu(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function bE(t){let e=Date.now();for(let r of["","-wal","-shm"])try{ZL(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Mu,ju,_o,Vi,ry,Wi,fs=b(()=>{"use strict";Mu=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let s=Object.values(n[0]);return s.length===1?s[0]:n[0]}exec(e){let r="",n=null;for(let o=0;o<e.length;o++){let i=e[o];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let s=r.trim();return s&&this.#e.prepare(s).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let s=r.get(...n);return s===null?void 0:s},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},ju=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let s=Object.values(n[0]);return s.length===1?s[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},_o=null;Vi=Symbol.for("__context_mode_live_dbs__"),ry=(()=>{let t=globalThis;return t[Vi]||(t[Vi]=new Set,process.on("exit",()=>{for(let e of t[Vi])bo(e);t[Vi].clear()})),t[Vi]})(),Wi=class{#e;#t;constructor(e){let r=Pt();this.#e=e,vo(e);let n;try{n=new r(e,{timeout:3e4}),xo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Lu(o)){bE(e),vo(e);try{n=new r(e,{timeout:3e4}),xo(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#t=n,ry.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){ry.delete(this.#t),bo(this.#t)}withRetry(e){return Sn(e)}cleanup(){ry.delete(this.#t),bo(this.#t),zu(this.#e)}}});import{readFileSync as kE,readdirSync as RE,unlinkSync as oy,existsSync as sy,statSync as Fu,openSync as wE,fstatSync as EE,closeSync as $E}from"node:fs";import{createHash as TE}from"node:crypto";import{tmpdir as CE}from"node:os";import{join as iy}from"node:path";function OE(t){let e=new Set,r=[];for(let n of t){let s=n.toLowerCase();e.has(s)||(e.add(s),r.push(n))}return r}function VL(t,e="AND"){let r=OE(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(o=>o.length>0&&!["AND","OR","NOT","NEAR"].includes(o.toUpperCase())));if(r.length===0)return'""';let n=r.filter(o=>!So.has(o.toLowerCase()));return(n.length>0?n:r).map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function WL(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=OE(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let s=n.filter(i=>!So.has(i.toLowerCase()));return(s.length>0?s:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function GL(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,s)=>s);for(let n=1;n<=t.length;n++){let s=[n];for(let o=1;o<=e.length;o++)s[o]=t[n-1]===e[o-1]?r[o-1]:1+Math.min(r[o],s[o-1],r[o-1]);r=s}return r[e.length]}function KL(t){return t<=4?1:t<=12?2:3}function ay(){let t=CE(),e=0;try{let r=RE(t);for(let n of r){let s=n.match(/^context-mode-(\d+)\.db$/);if(!s)continue;let o=parseInt(s[1],10);if(o!==process.pid)try{process.kill(o,0)}catch{let i=iy(t,n);for(let a of["","-wal","-shm"])try{oy(i+a)}catch{}e++}}}catch{}return e}function cy(t,e){let r=0;try{if(!sy(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=RE(t).filter(o=>o.endsWith(".db"));for(let o of s)try{let i=iy(t,o),c=Fu(i).mtimeMs<n;if(!c){let u=i+"-wal";if(sy(u))try{let d=Fu(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{oy(i+u)}catch{}r++}}catch{}}catch{}return r}function JL(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function YL(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,s=Math.min(t.length,e.length)-1;for(let o=0;o<s;o++){let i=t[o],a=t[o+1],c=e[o].length,u=0;for(let d of i){let l=d+c,p=l+r;for(;u<a.length&&a[u]<l;)u++;u<a.length&&a[u]<=p&&(n++,u++)}}return n}function XL(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(s=>[...s].sort((o,i)=>o-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let s=1/0,o=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<s&&(s=u,i=c),u>o&&(o=u)}let a=o-s;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var So,PE,Uu,IE=b(()=>{"use strict";fs();So=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"]);PE=4096;Uu=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#x;#v;#b;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=Pt();this.#t=e??iy(CE(),`context-mode-${process.pid}.db`),vo(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),xo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Lu(o)){zu(this.#t),vo(this.#t);try{n=new r(this.#t,{timeout:3e4}),xo(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#e=n,this.#H(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{oy(this.#t+e)}catch{}}#H(){this.#e.exec(`
143
143
  CREATE TABLE IF NOT EXISTS sources (
144
144
  id INTEGER PRIMARY KEY AUTOINCREMENT,
145
145
  label TEXT NOT NULL,
@@ -379,7 +379,7 @@ ${n}`}}}});import{cpus as ML}from"node:os";async function Qg(t,e){let{concurrenc
379
379
  (SELECT COUNT(*) FROM sources) AS sources,
380
380
  (SELECT COUNT(*) FROM chunks) AS chunks,
381
381
  (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
382
- `),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:s}=e,o=typeof r=="string"&&r.length>0;if(!o&&!n)throw new Error("Either content or path must be provided");let i;if(o)i=r;else{let l=kE(n,"r");try{if(!wE(l).isFile())throw new Error(`refusing to index ${n}: not a regular file`);i=SE(l,"utf-8")}finally{EE(l)}}let a=s??n??"untitled",c=this.#V(i),u=n??void 0,d=u?$E("sha256").update(i).digest("hex"):void 0;return Sn(()=>this.#d(c,a,i,u,d))}indexPlainText(e,r,n=20){if(!e||e.trim().length===0)return this.#d([],r,"");let s=this.#W(e,n);return Sn(()=>this.#d(s.map(o=>({...o,hasCode:!1})),r,e))}indexJSON(e,r,n=TE){if(!e||e.trim().length===0)return this.indexPlainText("",r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r)}let o=[];return this.#U(s,[],o,n),o.length===0?this.indexPlainText(e,r):Sn(()=>this.#d(o,r,e))}#d(e,r,n,s,o){let i=e.filter(u=>u.hasCode).length,c=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let p=this.#o.run(r,s??null,o??null);return Number(p.lastInsertRowid)}let u=this.#s.run(r,e.length,i,s??null,o??null),d=Number(u.lastInsertRowid),l=new Date().toISOString();for(let p of e){let f=p.hasCode?"code":"prose";this.#a.run(p.title,p.content,d,f,null,null,null,l),this.#c.run(p.title,p.content,d,f,null,null,null,l)}return d})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:c,label:r,totalChunks:e.length,codeChunks:i}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,s="AND",o,i="like"){let a=HL(e,s),c,u;return n&&o?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):o?(c=this.#b,u=[a,o,r]):(c=this.#f,u=[a,r]),Sn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,s="AND",o,i="like"){let a=ZL(e,s);if(!a)return[];let c,u;return n&&o?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#x:this.#_,u=[a,this.#p(n,i),r]):o?(c=this.#w,u=[a,o,r]):(c=this.#y,u=[a,r]),Sn(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=qL(r.length),s=this.#v.all(r.length-n,r.length+n),o=null,i=n+1,a=!1;for(let{word:u}of s){if(u===r){a=!0;break}let d=BL(r,u);d<i&&(i=d,o=u)}let c=a?null:i<=n?o:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#z(e,r,n,s,o="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",s,o),u=this.searchTrigram(e,a,n,"OR",s,o),d=new Map,l=p=>`${p.source}::${p.title}`;for(let[p,f]of c.entries()){let m=l(f),h=d.get(m);h?h.score+=1/(60+p+1):d.set(m,{result:f,score:1/(60+p+1)})}for(let[p,f]of u.entries()){let m=l(f),h=d.get(m);h?h.score+=1/(60+p+1):d.set(m,{result:f,score:1/(60+p+1)})}return Array.from(d.values()).sort((p,f)=>f.score-p.score).slice(0,r).map(({result:p,score:f})=>({...p,rank:-f}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),s=n.filter(i=>!So.has(i)),o=s.length>0?s:n;return e.map(i=>{let a=i.title.toLowerCase(),c=o.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/o.length):0,l=0,p=0;if(o.length>=2){let f=i.content.toLowerCase(),m=o.map(h=>VL(f,h));if(!m.some(h=>h.length===0)){l=1/(1+GL(m)/Math.max(f.length,1));let g=WL(m,o);p=.5*Math.min(1,g/4)}}return{result:i,boost:d+l+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,s,o="like"){this.#B();let i=this.#z(e,r,n,s,o);if(i.length>0)return this.#L(i,e).map(p=>({...p,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(l=>l.length>=3&&!So.has(l)),c=a.join(" "),d=a.map(l=>this.fuzzyCorrect(l)??l).join(" ");if(d!==c){let l=this.#z(d,r,n,s,o);if(l.length>0)return this.#L(l,d).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#B(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!ry(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Lu(r.file_path).mtime,s=new Date(r.indexed_at+"Z");if(n<=s)continue;let o=kE(r.file_path,"r"),i;try{if(!wE(o).isFile())continue;i=SE(o,"utf-8")}finally{EE(o)}if($E("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#T.all()}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#R.get(e);if(!n||n.chunk_count<3)return[];let s=n.chunk_count,o=2,i=Math.max(3,Math.ceil(s*.4)),a=new Map;for(let d of this.#C.iterate(e)){let l=new Set(d.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!So.has(p)));for(let p of l)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,d])=>d>=o&&d<=i).map(([d,l])=>{let p=Math.log(s/l),f=Math.min(d.length/20,.5),m=/[_]/.test(d),h=d.length>=12,g=m?1.5:h?.8:0;return{word:d,score:p+f+g}}).sort((d,l)=>l.score-d.score).slice(0,r).map(d=>d.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(s=>(this.#A.run(s),this.#N.run(s),this.#D.run(s)))(e).changes}getDBSizeBytes(){try{return Lu(this.#t).size}catch{return 0}}#F(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#F(),bo(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!So.has(o)),n=[...new Set(r)],s=0;this.#e.transaction(()=>{for(let o of n){let i=this.#i.run(o);s+=i.changes}})(),s>0&&this.#r.clear()}#V(e,r=TE){let n=[],s=e.split(`
382
+ `),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:s}=e,o=typeof r=="string"&&r.length>0;if(!o&&!n)throw new Error("Either content or path must be provided");let i;if(o)i=r;else{let l=wE(n,"r");try{if(!EE(l).isFile())throw new Error(`refusing to index ${n}: not a regular file`);i=kE(l,"utf-8")}finally{$E(l)}}let a=s??n??"untitled",c=this.#V(i),u=n??void 0,d=u?TE("sha256").update(i).digest("hex"):void 0;return Sn(()=>this.#d(c,a,i,u,d))}indexPlainText(e,r,n=20){if(!e||e.trim().length===0)return this.#d([],r,"");let s=this.#W(e,n);return Sn(()=>this.#d(s.map(o=>({...o,hasCode:!1})),r,e))}indexJSON(e,r,n=PE){if(!e||e.trim().length===0)return this.indexPlainText("",r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r)}let o=[];return this.#U(s,[],o,n),o.length===0?this.indexPlainText(e,r):Sn(()=>this.#d(o,r,e))}#d(e,r,n,s,o){let i=e.filter(u=>u.hasCode).length,c=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let p=this.#o.run(r,s??null,o??null);return Number(p.lastInsertRowid)}let u=this.#s.run(r,e.length,i,s??null,o??null),d=Number(u.lastInsertRowid),l=new Date().toISOString();for(let p of e){let f=p.hasCode?"code":"prose";this.#a.run(p.title,p.content,d,f,null,null,null,l),this.#c.run(p.title,p.content,d,f,null,null,null,l)}return d})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:c,label:r,totalChunks:e.length,codeChunks:i}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,s="AND",o,i="like"){let a=VL(e,s),c,u;return n&&o?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):o?(c=this.#b,u=[a,o,r]):(c=this.#f,u=[a,r]),Sn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,s="AND",o,i="like"){let a=WL(e,s);if(!a)return[];let c,u;return n&&o?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#x:this.#_,u=[a,this.#p(n,i),r]):o?(c=this.#w,u=[a,o,r]):(c=this.#y,u=[a,r]),Sn(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=KL(r.length),s=this.#v.all(r.length-n,r.length+n),o=null,i=n+1,a=!1;for(let{word:u}of s){if(u===r){a=!0;break}let d=GL(r,u);d<i&&(i=d,o=u)}let c=a?null:i<=n?o:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#z(e,r,n,s,o="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",s,o),u=this.searchTrigram(e,a,n,"OR",s,o),d=new Map,l=p=>`${p.source}::${p.title}`;for(let[p,f]of c.entries()){let m=l(f),h=d.get(m);h?h.score+=1/(60+p+1):d.set(m,{result:f,score:1/(60+p+1)})}for(let[p,f]of u.entries()){let m=l(f),h=d.get(m);h?h.score+=1/(60+p+1):d.set(m,{result:f,score:1/(60+p+1)})}return Array.from(d.values()).sort((p,f)=>f.score-p.score).slice(0,r).map(({result:p,score:f})=>({...p,rank:-f}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),s=n.filter(i=>!So.has(i)),o=s.length>0?s:n;return e.map(i=>{let a=i.title.toLowerCase(),c=o.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/o.length):0,l=0,p=0;if(o.length>=2){let f=i.content.toLowerCase(),m=o.map(h=>JL(f,h));if(!m.some(h=>h.length===0)){l=1/(1+XL(m)/Math.max(f.length,1));let g=YL(m,o);p=.5*Math.min(1,g/4)}}return{result:i,boost:d+l+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,s,o="like"){this.#B();let i=this.#z(e,r,n,s,o);if(i.length>0)return this.#L(i,e).map(p=>({...p,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(l=>l.length>=3&&!So.has(l)),c=a.join(" "),d=a.map(l=>this.fuzzyCorrect(l)??l).join(" ");if(d!==c){let l=this.#z(d,r,n,s,o);if(l.length>0)return this.#L(l,d).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#B(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!sy(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Fu(r.file_path).mtime,s=new Date(r.indexed_at+"Z");if(n<=s)continue;let o=wE(r.file_path,"r"),i;try{if(!EE(o).isFile())continue;i=kE(o,"utf-8")}finally{$E(o)}if(TE("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#T.all()}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#R.get(e);if(!n||n.chunk_count<3)return[];let s=n.chunk_count,o=2,i=Math.max(3,Math.ceil(s*.4)),a=new Map;for(let d of this.#C.iterate(e)){let l=new Set(d.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!So.has(p)));for(let p of l)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,d])=>d>=o&&d<=i).map(([d,l])=>{let p=Math.log(s/l),f=Math.min(d.length/20,.5),m=/[_]/.test(d),h=d.length>=12,g=m?1.5:h?.8:0;return{word:d,score:p+f+g}}).sort((d,l)=>l.score-d.score).slice(0,r).map(d=>d.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(s=>(this.#A.run(s),this.#N.run(s),this.#D.run(s)))(e).changes}getDBSizeBytes(){try{return Fu(this.#t).size}catch{return 0}}#F(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#F(),bo(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!So.has(o)),n=[...new Set(r)],s=0;this.#e.transaction(()=>{for(let o of n){let i=this.#i.run(o);s+=i.changes}})(),s>0&&this.#r.clear()}#V(e,r=PE){let n=[],s=e.split(`
383
383
  `),o=[],i=[],a="",c=()=>{let d=i.join(`
384
384
  `).trim();if(d.length===0)return;let l=this.#Y(o,a),p=i.some(_=>/^`{3,}/.test(_));if(Buffer.byteLength(d)<=r){n.push({title:l,content:d,hasCode:p}),i=[];return}let f=d.split(/\n\n+/),m=[],h=1,g=()=>{if(m.length===0)return;let _=m.join(`
385
385
 
@@ -388,13 +388,13 @@ ${n}`}}}});import{cpus as ML}from"node:os";async function Qg(t,e){let{concurrenc
388
388
  `);Buffer.byteLength(v)>r&&m.length>1&&(m.pop(),g(),m=[_])}g(),i=[]},u=0;for(;u<s.length;){let d=s[u];if(/^[-_*]{3,}\s*$/.test(d)){c(),u++;continue}let l=d.match(/^(#{1,4})\s+(.+)$/);if(l){c();let f=l[1].length,m=l[2].trim();for(;o.length>0&&o[o.length-1].level>=f;)o.pop();o.push({level:f,text:m}),a=m,i.push(d),u++;continue}let p=d.match(/^(`{3,})(.*)?$/);if(p){let f=p[1],m=[d];for(u++;u<s.length;){if(m.push(s[u]),s[u].startsWith(f)&&s[u].trim()===f){u++;break}u++}i.push(...m);continue}i.push(d),u++}return c(),n}#W(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let d=c.trim();return{title:d.split(`
389
389
  `)[0].slice(0,80)||`Section ${u+1}`,content:d}}).filter(c=>c.content.length>0);let s=e.split(`
390
390
  `);if(s.length<=r)return[{title:"Output",content:e}];let o=[],a=Math.max(r-2,1);for(let c=0;c<s.length;c+=a){let u=s.slice(c,c+r);if(u.length===0)break;let d=c+1,l=Math.min(c+u.length,s.length),p=u[0]?.trim().slice(0,80);o.push({title:p||`Lines ${d}-${l}`,content:u.join(`
391
- `)})}return o}#U(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=s&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:o,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...r,c],n,s);return}n.push({title:o,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,s);return}n.push({title:o,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],s=r;for(let o of n)if(o in s&&(typeof s[o]=="string"||typeof s[o]=="number"))return o;return null}#K(e,r,n,s,o){let i=e?`${e} > `:"";if(!o)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[o]);return s.length===1?`${i}${a(s[0])}`:s.length<=3?i+s.map(a).join(", "):`${i}${a(s[0])}\u2026${a(s[s.length-1])}`}#J(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=d=>{if(a.length===0)return;let l=this.#K(o,c,d,a,i);n.push({title:l,content:JSON.stringify(a,null,2),hasCode:!0})};for(let d=0;d<e.length;d++){a.push(e[d]);let l=JSON.stringify(a,null,2);Buffer.byteLength(l)>s&&a.length>1&&(a.pop(),u(d-1),a=[e[d]],c=d)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function ay(t,e){return t===void 0?e:`${t}::${e}`}var IE=b(()=>{"use strict"});import{readFileSync as NE,realpathSync as KL}from"node:fs";import{resolve as Wi}from"node:path";function DE(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function JL(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function YL(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function AE(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function XL(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let s=t.slice(0,n),o=t.slice(n+1),i=YL(s),a=AE(o);r=`^${i}(\\s${a})?$`}else r=`^${AE(t)}$`;return new RegExp(r,e?"i":"")}function QL(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function eF(t,e,r=!1){for(let n of e){let s=DE(n);if(s&&XL(s,r).test(t))return n}return null}function tF(t){let e=[],r="",n=!1,s=!1,o=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!s&&!o&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!o&&c!=="\\"?(s=!s,r+=a):a==="`"&&!n&&!s&&c!=="\\"?(o=!o,r+=a):!n&&!s&&!o?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function cy(t){let e;try{e=NE(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let s=o=>Array.isArray(o)?o.filter(i=>typeof i=="string"&&DE(i)!==null):[];return{allow:s(n.allow),deny:s(n.deny),ask:s(n.ask)}}function uy(t,e){let r=[];if(t){let s=Wi(t,".claude","settings.local.json"),o=cy(s);o&&r.push(o);let i=Wi(t,".claude","settings.json"),a=cy(i);a&&r.push(a)}let n=e!==void 0?[e]:Al();for(let s of n){let o=cy(s);o&&r.push(o)}return r}function ly(t,e,r){let n=[],s=i=>{let a;try{a=NE(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let d=[];for(let l of u){if(typeof l!="string")continue;let p=JL(l);p&&p.tool===t&&d.push(p.glob)}return d};if(e){let i=s(Wi(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=s(Wi(e,".claude","settings.json"));a!==null&&n.push(a)}let o=r!==void 0?[r]:Al();for(let i of o){let a=s(i);a!==null&&n.push(a)}return n}function dy(t,e,r=process.platform==="win32"){let n=tF(t);for(let s of n)for(let o of e){let i=eF(s,o.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function py(t,e,r=process.platform==="win32",n){let s=i=>i.replace(/\\/g,"/"),o=new Set;if(o.add(s(t)),n){let i=Wi(n,t);o.add(s(i));try{o.add(s(KL(i)))}catch{}}for(let i of e)for(let a of i){let c=QL(s(a),r);for(let u of o)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function nF(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let o=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);o.length>0&&e.push(o.join(" "))}return e}function ME(t,e){let r=rF[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let s of r){s.lastIndex=0;let o;for(;(o=s.exec(t))!==null;){let i=o[o.length-1];i&&n.push(i)}}return e==="python"&&n.push(...nF(t)),n}var rF,jE=b(()=>{"use strict";Yr();rF={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});function my(t){let{language:e,exitCode:r,stdout:n,stderr:s}=t,o=e==="shell"&&r===1&&n.trim().length>0;return{isError:!o,output:o?n:`Exit code: ${r}
391
+ `)})}return o}#U(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=s&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:o,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...r,c],n,s);return}n.push({title:o,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,s);return}n.push({title:o,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],s=r;for(let o of n)if(o in s&&(typeof s[o]=="string"||typeof s[o]=="number"))return o;return null}#K(e,r,n,s,o){let i=e?`${e} > `:"";if(!o)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[o]);return s.length===1?`${i}${a(s[0])}`:s.length<=3?i+s.map(a).join(", "):`${i}${a(s[0])}\u2026${a(s[s.length-1])}`}#J(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=d=>{if(a.length===0)return;let l=this.#K(o,c,d,a,i);n.push({title:l,content:JSON.stringify(a,null,2),hasCode:!0})};for(let d=0;d<e.length;d++){a.push(e[d]);let l=JSON.stringify(a,null,2);Buffer.byteLength(l)>s&&a.length>1&&(a.pop(),u(d-1),a=[e[d]],c=d)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function uy(t,e){return t===void 0?e:`${t}::${e}`}var AE=b(()=>{"use strict"});import{readFileSync as DE,realpathSync as QL}from"node:fs";import{resolve as Gi}from"node:path";function ME(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function eF(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function tF(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function NE(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function rF(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let s=t.slice(0,n),o=t.slice(n+1),i=tF(s),a=NE(o);r=`^${i}(\\s${a})?$`}else r=`^${NE(t)}$`;return new RegExp(r,e?"i":"")}function nF(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function sF(t,e,r=!1){for(let n of e){let s=ME(n);if(s&&rF(s,r).test(t))return n}return null}function oF(t){let e=[],r="",n=!1,s=!1,o=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!s&&!o&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!o&&c!=="\\"?(s=!s,r+=a):a==="`"&&!n&&!s&&c!=="\\"?(o=!o,r+=a):!n&&!s&&!o?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function ly(t){let e;try{e=DE(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let s=o=>Array.isArray(o)?o.filter(i=>typeof i=="string"&&ME(i)!==null):[];return{allow:s(n.allow),deny:s(n.deny),ask:s(n.ask)}}function dy(t,e){let r=[];if(t){let s=Gi(t,".claude","settings.local.json"),o=ly(s);o&&r.push(o);let i=Gi(t,".claude","settings.json"),a=ly(i);a&&r.push(a)}let n=e!==void 0?[e]:Nl();for(let s of n){let o=ly(s);o&&r.push(o)}return r}function py(t,e,r){let n=[],s=i=>{let a;try{a=DE(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let d=[];for(let l of u){if(typeof l!="string")continue;let p=eF(l);p&&p.tool===t&&d.push(p.glob)}return d};if(e){let i=s(Gi(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=s(Gi(e,".claude","settings.json"));a!==null&&n.push(a)}let o=r!==void 0?[r]:Nl();for(let i of o){let a=s(i);a!==null&&n.push(a)}return n}function my(t,e,r=process.platform==="win32"){let n=oF(t);for(let s of n)for(let o of e){let i=sF(s,o.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function fy(t,e,r=process.platform==="win32",n){let s=i=>i.replace(/\\/g,"/"),o=new Set;if(o.add(s(t)),n){let i=Gi(n,t);o.add(s(i));try{o.add(s(QL(i)))}catch{}}for(let i of e)for(let a of i){let c=nF(s(a),r);for(let u of o)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function aF(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let o=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);o.length>0&&e.push(o.join(" "))}return e}function jE(t,e){let r=iF[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let s of r){s.lastIndex=0;let o;for(;(o=s.exec(t))!==null;){let i=o[o.length-1];i&&n.push(i)}}return e==="python"&&n.push(...aF(t)),n}var iF,zE=b(()=>{"use strict";Yr();iF={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});function hy(t){let{language:e,exitCode:r,stdout:n,stderr:s}=t,o=e==="shell"&&r===1&&n.trim().length>0;return{isError:!o,output:o?n:`Exit code: ${r}
392
392
 
393
393
  stdout:
394
394
  ${n}
395
395
 
396
396
  stderr:
397
- ${s}`}}var zE=b(()=>{"use strict"});import{execFileSync as sF}from"node:child_process";function oF(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=sF("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function iF(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??oF,n=e(),s=r();return()=>{let o=e();return!(o!==n||o===0||o===1||!Number.isNaN(s)&&s>1&&r()===1)}}function cF(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function LE(t){let e=t.checkIntervalMs??cF(),r=t.isParentAlive??aF,n=!1,s=()=>{n||(n=!0,t.onShutdown())},o=setInterval(()=>{r()||s()},e);o.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,s);let a=()=>{r()||s()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(o);for(let c of i)process.removeListener(c,s);process.stdin.removeListener("end",a)}}var aF,FE=b(()=>{"use strict";aF=iF()});import{createHash as Ki}from"node:crypto";import{execFileSync as uF}from"node:child_process";import{existsSync as Hu,realpathSync as lF,renameSync as fy}from"node:fs";import{join as Zu}from"node:path";function Ji(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function UE(t){let e=t;try{e=lF.native(t)}catch{}let r=Ji(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function BE(t,e){return uF("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function dF(t){let e=BE(t,["rev-parse","--show-toplevel"]);return e.length>0?Ji(e):null}function pF(t){let e=BE(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?Ji(e):null}function Bu(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Gi&&Gi.projectDir===t&&Gi.envSuffix===e)return Gi.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=dF(t),s=pF(t);if(n&&s){let o=UE(n),i=UE(s);o!==i&&(r=`__${Ki("sha256").update(o).digest("hex").slice(0,8)}`)}}catch{}return Gi={projectDir:t,envSuffix:e,suffix:r},r}function Hr(t){return Ki("sha256").update(Ji(t)).digest("hex").slice(0,16)}function Zr(t){let e=Ji(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Ki("sha256").update(r).digest("hex").slice(0,16)}function qE(t){let{projectDir:e,contentDir:r}=t,n=Zr(e),s=Zu(r,`${n}.db`);if(Hu(s))return s;let o=Hr(e);if(o===n)return s;let i=Zu(r,`${o}.db`);if(Hu(i))try{fy(i,s);for(let a of["-wal","-shm"])try{fy(i+a,s+a)}catch{}}catch{}return s}function qu(t){return mF({...t,ext:".db"})}function mF(t){let{projectDir:e,sessionsDir:r,ext:n}=t,s=t.suffix??Bu(e),o=Zr(e),i=Zu(r,`${o}${s}${n}`);if(Hu(i))return i;let a=Hr(e);if(a===o)return i;let c=Zu(r,`${a}${s}${n}`);if(Hu(c))try{fy(c,i)}catch{}return i}function Uu(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var Gi,HE,ZE,q,fr,Yi=b(()=>{"use strict";ms();HE=1e3,ZE=5;q={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},fr=class extends Vi{constructor(e){super(e?.dbPath??ty("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
397
+ ${s}`}}var LE=b(()=>{"use strict"});import{execFileSync as cF}from"node:child_process";function uF(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=cF("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function lF(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??uF,n=e(),s=r();return()=>{let o=e();return!(o!==n||o===0||o===1||!Number.isNaN(s)&&s>1&&r()===1)}}function pF(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function FE(t){let e=t.checkIntervalMs??pF(),r=t.isParentAlive??dF,n=!1,s=()=>{n||(n=!0,t.onShutdown())},o=setInterval(()=>{r()||s()},e);o.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,s);let a=()=>{r()||s()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(o);for(let c of i)process.removeListener(c,s);process.stdin.removeListener("end",a)}}var dF,UE=b(()=>{"use strict";dF=lF()});import{createHash as Ji}from"node:crypto";import{execFileSync as mF}from"node:child_process";import{existsSync as Zu,realpathSync as fF,renameSync as gy}from"node:fs";import{join as Bu}from"node:path";function Yi(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function HE(t){let e=t;try{e=fF.native(t)}catch{}let r=Yi(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function qE(t,e){return mF("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function hF(t){let e=qE(t,["rev-parse","--show-toplevel"]);return e.length>0?Yi(e):null}function gF(t){let e=qE(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?Yi(e):null}function qu(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Ki&&Ki.projectDir===t&&Ki.envSuffix===e)return Ki.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=hF(t),s=gF(t);if(n&&s){let o=HE(n),i=HE(s);o!==i&&(r=`__${Ji("sha256").update(o).digest("hex").slice(0,8)}`)}}catch{}return Ki={projectDir:t,envSuffix:e,suffix:r},r}function Hr(t){return Ji("sha256").update(Yi(t)).digest("hex").slice(0,16)}function Zr(t){let e=Yi(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Ji("sha256").update(r).digest("hex").slice(0,16)}function VE(t){let{projectDir:e,contentDir:r}=t,n=Zr(e),s=Bu(r,`${n}.db`);if(Zu(s))return s;let o=Hr(e);if(o===n)return s;let i=Bu(r,`${o}.db`);if(Zu(i))try{gy(i,s);for(let a of["-wal","-shm"])try{gy(i+a,s+a)}catch{}}catch{}return s}function Vu(t){return yF({...t,ext:".db"})}function yF(t){let{projectDir:e,sessionsDir:r,ext:n}=t,s=t.suffix??qu(e),o=Zr(e),i=Bu(r,`${o}${s}${n}`);if(Zu(i))return i;let a=Hr(e);if(a===o)return i;let c=Bu(r,`${a}${s}${n}`);if(Zu(c))try{gy(c,i)}catch{}return i}function Hu(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var Ki,ZE,BE,q,fr,Xi=b(()=>{"use strict";fs();ZE=1e3,BE=5;q={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},fr=class extends Wi{constructor(e){super(e?.dbPath??ny("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
398
398
  CREATE TABLE IF NOT EXISTS session_events (
399
399
  id INTEGER PRIMARY KEY AUTOINCREMENT,
400
400
  session_id TEXT NOT NULL,
@@ -512,17 +512,17 @@ ${s}`}}var zE=b(()=>{"use strict"});import{execFileSync as sF}from"node:child_pr
512
512
  FROM tool_calls WHERE session_id = ?`),e(q.getToolCallByTool,`SELECT tool, calls, bytes_returned
513
513
  FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(q.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
514
514
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
515
- FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=Ki("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(s?.projectDir??r.project_dir??"").trim(),c=String(s?.source??r.attribution_source??"unknown"),u=Number(s?.confidence??r.attribution_confidence??0),d=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,l=Uu(o?.bytesAvoided),p=Uu(o?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(q.checkDuplicate).get(e,ZE,r.type,i))return;this.stmt(q.getEventCount).get(e).cnt>=HE&&this.stmt(q.evictLowestPriority).run(e),this.stmt(q.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,p,n,i),this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,r,n="PostToolUse",s,o){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,s?.[0],o?.[0]);return}let i=r.map((c,u)=>{let d=Ki("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=s?.[u],p=String(l?.projectDir??c.project_dir??"").trim(),f=String(l?.source??c.attribution_source??"unknown"),m=Number(l?.confidence??c.attribution_confidence??0),h=Number.isFinite(m)?Math.max(0,Math.min(1,m)):0,g=o?.[u],_=Uu(g?.bytesAvoided),v=Uu(g?.bytesReturned);return{event:c,dataHash:d,projectDir:p,attributionSource:f,attributionConfidence:h,bytesAvoided:_,bytesReturned:v}}),a=this.db.transaction(()=>{let c=this.stmt(q.getEventCount).get(e).cnt;for(let u of i)this.stmt(q.checkDuplicate).get(e,ZE,u.event.type,u.dataHash)||(c>=HE?this.stmt(q.evictLowestPriority).run(e):c++,this.stmt(q.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,s=r?.type,o=r?.minPriority;return s&&o!==void 0?this.stmt(q.getEventsByTypeAndPriority).all(e,s,o,n):s?this.stmt(q.getEventsByType).all(e,s,n):o!==void 0?this.stmt(q.getEventsByPriority).all(e,o,n):this.stmt(q.getEvents).all(e,n)}getEventCount(e){return this.stmt(q.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(q.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(q.getLatestAttributedProject).get(e)?.project_dir||null}searchEvents(e,r,n,s){try{let o=e.replace(/[%_]/g,a=>"\\"+a),i=s??null;return this.stmt(q.searchEvents).all(n,o,o,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(q.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(q.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(q.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(q.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(q.getResume).get(e)??null}markResumeConsumed(e){this.stmt(q.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(q.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let s=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(q.incrementToolCall).run(e,r,s)}catch{}}getToolCallStats(e){try{let r=this.stmt(q.getToolCallTotals).get(e),n=this.stmt(q.getToolCallByTool).all(e),s={};for(let o of n)s[o.tool]={calls:o.calls,bytesReturned:o.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:s}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(q.deleteEvents).run(e),this.stmt(q.deleteResume).run(e),this.stmt(q.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(q.getOldSessions).all(r);for(let{session_id:s}of n)this.deleteSession(s);return n.length}}});import{existsSync as hy,unlinkSync as fF}from"node:fs";import{join as Xi}from"node:path";function gy(t,e){try{return fF(t),e.push(t),!0}catch{return!1}}function Vu(t,e){let r=!1;for(let n of hF)gy(`${t}${n}`,e)&&n===""&&(r=!0);return r}function VE(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:s,legacyContentDir:o,contentHash:i,sessionId:a,scope:c}=t,u=[],d=[],l=c??(a?"session":"project");if(l==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(l==="session"&&a){let y=Bu(e),x=Zr(e),k=Hr(e),R=x===k?[x]:[x,k],$=!1;for(let T of R){let C=Xi(r,`${T}${y}.db`);if(!hy(C))continue;let L=null;try{L=new fr({dbPath:C});let X=L.getEvents(a).length;L.deleteSession(a),X>0&&($=!0)}catch{}finally{try{L?.close()}catch{}}}$&&u.push(`session rows for ${a}`);let P=[];if(n&&hy(n)&&P.push(n),s){let T=Zr(e),C=Hr(e),L=T===C?[T]:[T,C];for(let X of L){let ae=Xi(s,`${X}.db`);hy(ae)&&!P.includes(ae)&&P.push(ae)}}let j=!1;for(let T of P)try{let C=Pt(),L=new C(T,{timeout:3e4});try{let X=L.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;L.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),L.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),X>0&&(j=!0)}finally{try{L.close()}catch{}}}catch{}return j&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:d}}let p=!1;if(n&&Vu(n,d)&&(p=!0),s){let y=Zr(e),x=Hr(e),k=y===x?[y]:[y,x];for(let R of k){let $=Xi(s,`${R}.db`);Vu($,d)&&(p=!0)}}if(p&&u.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let y=Xi(o,`${i}.db`);Vu(y,d)}let f=Bu(e),m=Zr(e),h=Hr(e),g=m===h?[m]:[m,h],_=!1,v=!1;for(let y of g){let x=Xi(r,`${y}${f}`);Vu(`${x}.db`,d)&&(_=!0),gy(`${x}-events.md`,d)&&(v=!0),gy(`${x}.cleanup`,d)}return _&&u.push("session events DB"),v&&u.push("session events markdown"),{deleted:u,wipedPaths:d}}var hF,WE=b(()=>{"use strict";ms();Yi();hF=["","-wal","-shm"]});import{existsSync as gF}from"node:fs";function yy(t,e){try{if(!gF(t))return;let r=new fr({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function GE(t){yy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function KE(t){yy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function JE(t){yy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var YE=b(()=>{"use strict";Yi()});import{existsSync as XE}from"node:fs";function QE(t,e,r){try{if(!XE(t))return;let n=new fr({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function e$(t){try{if(!XE(t))return null;let e=new fr({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),s={},o={};for(let[a,c]of Object.entries(n.byTool))s[a]=c.calls,o[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(s).length===0&&Object.keys(o).length===0?{calls:s,bytesReturned:o,sessionStart:i}:{calls:s,bytesReturned:o,sessionStart:i}}finally{e.close()}}catch{return null}}var t$=b(()=>{"use strict";Yi()});import{existsSync as _y,readFileSync as yF,readdirSync as _F,statSync as xF}from"node:fs";import{join as Qi,isAbsolute as vF}from"node:path";function s$(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?n$(r,a):null)??n??Ze(),d=s?.getMemoryDir(),l=d?n$(r,d):Qi(u,"memory"),p=[];if(r)for(let f of i){let m=Qi(r,f);_y(m)&&p.push({path:m,label:`project/${f}`})}if(u&&u!==r)for(let f of i){let m=Qi(u,f);_y(m)&&p.push({path:m,label:`user/${f}`})}if(l&&_y(l))try{let f=_F(l).filter(m=>m.endsWith(".md"));for(let m of f)p.push({path:Qi(l,m),label:`memory/${m}`})}catch(f){r$&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
516
- `)}for(let f of p){if(o.length>=e)break;try{let m;try{if(m=xF(f.path),m.size>1e6)continue}catch{continue}let h=yF(f.path,"utf-8"),g=h.toLowerCase();for(let _ of t){if(o.length>=e)break;let y=_.toLowerCase().split(/\s+/).filter(k=>k.length>=3);if(y.some(k=>{try{return new RegExp(`\\b${k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(h)}catch{return g.includes(k)}})){let k=y.reduce((C,L)=>{let X=g.indexOf(L);return X>=0&&(C<0||X<C)?X:C},-1),R=Math.max(0,k-200),$=Math.min(h.length,k+500),P=h.lastIndexOf(`
515
+ FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=Ji("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(s?.projectDir??r.project_dir??"").trim(),c=String(s?.source??r.attribution_source??"unknown"),u=Number(s?.confidence??r.attribution_confidence??0),d=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,l=Hu(o?.bytesAvoided),p=Hu(o?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(q.checkDuplicate).get(e,BE,r.type,i))return;this.stmt(q.getEventCount).get(e).cnt>=ZE&&this.stmt(q.evictLowestPriority).run(e),this.stmt(q.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,p,n,i),this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,r,n="PostToolUse",s,o){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,s?.[0],o?.[0]);return}let i=r.map((c,u)=>{let d=Ji("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=s?.[u],p=String(l?.projectDir??c.project_dir??"").trim(),f=String(l?.source??c.attribution_source??"unknown"),m=Number(l?.confidence??c.attribution_confidence??0),h=Number.isFinite(m)?Math.max(0,Math.min(1,m)):0,g=o?.[u],_=Hu(g?.bytesAvoided),v=Hu(g?.bytesReturned);return{event:c,dataHash:d,projectDir:p,attributionSource:f,attributionConfidence:h,bytesAvoided:_,bytesReturned:v}}),a=this.db.transaction(()=>{let c=this.stmt(q.getEventCount).get(e).cnt;for(let u of i)this.stmt(q.checkDuplicate).get(e,BE,u.event.type,u.dataHash)||(c>=ZE?this.stmt(q.evictLowestPriority).run(e):c++,this.stmt(q.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,s=r?.type,o=r?.minPriority;return s&&o!==void 0?this.stmt(q.getEventsByTypeAndPriority).all(e,s,o,n):s?this.stmt(q.getEventsByType).all(e,s,n):o!==void 0?this.stmt(q.getEventsByPriority).all(e,o,n):this.stmt(q.getEvents).all(e,n)}getEventCount(e){return this.stmt(q.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(q.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(q.getLatestAttributedProject).get(e)?.project_dir||null}searchEvents(e,r,n,s){try{let o=e.replace(/[%_]/g,a=>"\\"+a),i=s??null;return this.stmt(q.searchEvents).all(n,o,o,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(q.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(q.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(q.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(q.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(q.getResume).get(e)??null}markResumeConsumed(e){this.stmt(q.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(q.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let s=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(q.incrementToolCall).run(e,r,s)}catch{}}getToolCallStats(e){try{let r=this.stmt(q.getToolCallTotals).get(e),n=this.stmt(q.getToolCallByTool).all(e),s={};for(let o of n)s[o.tool]={calls:o.calls,bytesReturned:o.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:s}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(q.deleteEvents).run(e),this.stmt(q.deleteResume).run(e),this.stmt(q.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(q.getOldSessions).all(r);for(let{session_id:s}of n)this.deleteSession(s);return n.length}}});import{existsSync as yy,unlinkSync as _F}from"node:fs";import{join as Qi}from"node:path";function _y(t,e){try{return _F(t),e.push(t),!0}catch{return!1}}function Wu(t,e){let r=!1;for(let n of xF)_y(`${t}${n}`,e)&&n===""&&(r=!0);return r}function WE(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:s,legacyContentDir:o,contentHash:i,sessionId:a,scope:c}=t,u=[],d=[],l=c??(a?"session":"project");if(l==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(l==="session"&&a){let y=qu(e),x=Zr(e),k=Hr(e),R=x===k?[x]:[x,k],$=!1;for(let T of R){let C=Qi(r,`${T}${y}.db`);if(!yy(C))continue;let L=null;try{L=new fr({dbPath:C});let X=L.getEvents(a).length;L.deleteSession(a),X>0&&($=!0)}catch{}finally{try{L?.close()}catch{}}}$&&u.push(`session rows for ${a}`);let P=[];if(n&&yy(n)&&P.push(n),s){let T=Zr(e),C=Hr(e),L=T===C?[T]:[T,C];for(let X of L){let ae=Qi(s,`${X}.db`);yy(ae)&&!P.includes(ae)&&P.push(ae)}}let j=!1;for(let T of P)try{let C=Pt(),L=new C(T,{timeout:3e4});try{let X=L.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;L.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),L.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),X>0&&(j=!0)}finally{try{L.close()}catch{}}}catch{}return j&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:d}}let p=!1;if(n&&Wu(n,d)&&(p=!0),s){let y=Zr(e),x=Hr(e),k=y===x?[y]:[y,x];for(let R of k){let $=Qi(s,`${R}.db`);Wu($,d)&&(p=!0)}}if(p&&u.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let y=Qi(o,`${i}.db`);Wu(y,d)}let f=qu(e),m=Zr(e),h=Hr(e),g=m===h?[m]:[m,h],_=!1,v=!1;for(let y of g){let x=Qi(r,`${y}${f}`);Wu(`${x}.db`,d)&&(_=!0),_y(`${x}-events.md`,d)&&(v=!0),_y(`${x}.cleanup`,d)}return _&&u.push("session events DB"),v&&u.push("session events markdown"),{deleted:u,wipedPaths:d}}var xF,GE=b(()=>{"use strict";fs();Xi();xF=["","-wal","-shm"]});import{existsSync as vF}from"node:fs";function xy(t,e){try{if(!vF(t))return;let r=new fr({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function KE(t){xy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function JE(t){xy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function YE(t){xy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var XE=b(()=>{"use strict";Xi()});import{existsSync as QE}from"node:fs";function e$(t,e,r){try{if(!QE(t))return;let n=new fr({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function t$(t){try{if(!QE(t))return null;let e=new fr({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),s={},o={};for(let[a,c]of Object.entries(n.byTool))s[a]=c.calls,o[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(s).length===0&&Object.keys(o).length===0?{calls:s,bytesReturned:o,sessionStart:i}:{calls:s,bytesReturned:o,sessionStart:i}}finally{e.close()}}catch{return null}}var r$=b(()=>{"use strict";Xi()});import{existsSync as vy,readFileSync as bF,readdirSync as SF,statSync as kF}from"node:fs";import{join as ea,isAbsolute as wF}from"node:path";function o$(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?s$(r,a):null)??n??Ze(),d=s?.getMemoryDir(),l=d?s$(r,d):ea(u,"memory"),p=[];if(r)for(let f of i){let m=ea(r,f);vy(m)&&p.push({path:m,label:`project/${f}`})}if(u&&u!==r)for(let f of i){let m=ea(u,f);vy(m)&&p.push({path:m,label:`user/${f}`})}if(l&&vy(l))try{let f=SF(l).filter(m=>m.endsWith(".md"));for(let m of f)p.push({path:ea(l,m),label:`memory/${m}`})}catch(f){n$&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
516
+ `)}for(let f of p){if(o.length>=e)break;try{let m;try{if(m=kF(f.path),m.size>1e6)continue}catch{continue}let h=bF(f.path,"utf-8"),g=h.toLowerCase();for(let _ of t){if(o.length>=e)break;let y=_.toLowerCase().split(/\s+/).filter(k=>k.length>=3);if(y.some(k=>{try{return new RegExp(`\\b${k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(h)}catch{return g.includes(k)}})){let k=y.reduce((C,L)=>{let X=g.indexOf(L);return X>=0&&(C<0||X<C)?X:C},-1),R=Math.max(0,k-200),$=Math.min(h.length,k+500),P=h.lastIndexOf(`
517
517
 
518
518
  `,R),j=h.indexOf(`
519
519
 
520
- `,$);P>=0&&(R=P+2),j>=0&&($=j);let T=h.slice(R,$).trim();o.push({title:`[auto-memory] ${f.label}`,content:T,source:f.label,origin:"auto-memory",timestamp:m.mtime.toISOString()});break}}}catch(m){r$&&process.stderr.write(`[ctx] auto-memory file read failed: ${m}
521
- `)}}return o.slice(0,e)}function n$(t,e){return e?vF(e)||!t?e:Qi(t,e):t??""}var r$,o$=b(()=>{"use strict";Yr();r$=process.env.DEBUG?.includes("context-mode")});function i$(t){let{query:e,limit:r,store:n,sort:s="relevance",source:o,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:d}=t,l=[],p=new Date().toISOString();try{let f=n.searchWithFallback(e,r,o,i);l.push(...f.map(m=>({title:m.title,content:m.content,source:m.source,origin:"current-session",timestamp:m.timestamp||p,rank:m.rank,matchLayer:m.matchLayer,highlighted:m.highlighted,contentType:m.contentType})))}catch(f){xy&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
522
- `)}if(s==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",o);l.push(...f.map(m=>({title:`[${m.category}] ${m.type}`,content:m.data,source:"prior-session",origin:"prior-session",timestamp:m.created_at})))}}catch(f){xy&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
523
- `)}try{let f=s$([e],r,c,u,d);l.push(...f)}catch(f){xy&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
524
- `)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((f,m)=>(f.timestamp||"").localeCompare(m.timestamp||"")),l.slice(0,r)}var xy,a$=b(()=>{"use strict";o$();xy=process.env.DEBUG?.includes("context-mode")});import*as Rt from"node:fs";import*as by from"node:path";function vy(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function bF(t){if(!Rt.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Rt.readdirSync(t.projectsRoot)){let s=by.join(t.projectsRoot,n),o;try{o=Rt.statSync(s)}catch{continue}if(!o.isDirectory())continue;let i;try{i=Rt.readdirSync(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=by.join(s,a);try{let u=Rt.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e)try{let n=Rt.openSync(e,"r");try{let s=Buffer.alloc(8192),o=Rt.readSync(n,s,0,s.length,0),i=s.subarray(0,o).toString("utf-8");for(let a of i.split(`
525
- `).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{Rt.closeSync(n)}}catch{}}function c$(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:s}=t,o=[e.CLAUDE_PROJECT_DIR,e.GEMINI_PROJECT_DIR,e.VSCODE_CWD,e.OPENCODE_PROJECT_DIR,e.PI_PROJECT_DIR,e.IDEA_INITIAL_DIRECTORY,e.CURSOR_CWD,e.CONTEXT_MODE_PROJECT_DIR];for(let i of o)if(i&&!vy(i))return i;if(s){let i=bF({projectsRoot:s});if(i&&!vy(i))return i}return n&&!vy(n)?n:r}var u$=b(()=>{"use strict"});import{execFileSync as SF}from"node:child_process";import{existsSync as fs,readdirSync as ko,statSync as kF}from"node:fs";import{homedir as Ju}from"node:os";import{join as Dt,sep as wF}from"node:path";function y$(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function $F(t){let e=t?.home??Ju();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,s])=>{let o=Dt(e,...s,"context-mode");return{name:n,sessionsDir:Dt(o,"sessions"),contentDir:Dt(o,"content")}})}function TF(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function ea(t){let e=Ze(),r=t?.sessionsDir??Dt(e,"context-mode","sessions"),n=t?.memoryRoot??Dt(e,"projects"),s=0,o=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(fs(r)){let f=[];try{f=ko(r).filter(m=>m.endsWith(".db"))}catch{}if(f.length>0){let m=null;try{m=t?.loadDatabase?t.loadDatabase():Pt()}catch{}if(m)for(let h of f){let g=Dt(r,h);try{let _=new m(g,{readonly:!0});try{let v=_.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),y=_.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=v?.cnt??0,o+=y?.cnt??0;try{let x=_.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let k of x)k.category&&(u[k.category]=(u[k.category]??0)+(k.cnt??0))}catch{}try{let x=_.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();x?.bytes&&(i+=x.bytes)}catch{}try{let x=_.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(x?.t){let k=x.t.endsWith("Z")?x.t:x.t+"Z",R=Date.parse(k);Number.isFinite(R)&&R<a&&(a=R)}}catch{}try{let x=_.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let k of x)k.p&&c.add(k.p)}catch{}}finally{_.close()}}catch{}}}}let d=0,l=0,p={};if(fs(n)){let f=[];try{f=ko(n).filter(m=>{try{return kF(Dt(n,m)).isDirectory()}catch{return!1}})}catch{}for(let m of f){let h=Dt(n,m,"memory");if(!fs(h))continue;let g=[];try{g=ko(h).filter(_=>_.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let _ of g){let v=TF(_);p[v]=(p[v]??0)+1}}}}return{totalEvents:s,totalSessions:o,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:p,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function _$(t){let e=t.sessionsDir??Dt(Ju(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!fs(e))return n;let s=[];try{s=ko(e).filter(y=>!(!y.endsWith(".db")||t.worktreeHash&&!y.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():Pt()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,p=0,f=0,m=new Map,h=y=>Math.floor(y/864e5)*864e5;for(let y of s){let x=Dt(e,y),k=!1;try{let R=new o(x,{readonly:!0});try{let $=R.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let j of $)j.category&&(i[j.category]=(i[j.category]??0)+(j.cnt??0),a+=j.cnt??0,k=!0);let P=R.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(P?.mn){let j=Date.parse(P.mn+(P.mn.endsWith("Z")?"":"Z"));Number.isFinite(j)&&j<l&&(l=j)}if(P?.mx){let j=Date.parse(P.mx+(P.mx.endsWith("Z")?"":"Z"));Number.isFinite(j)&&j>p&&(p=j)}try{let j=R.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let T of j){if(!T.sec)continue;let C=parseInt(T.sec,10)*1e3;if(!Number.isFinite(C))continue;let L=h(C),X=m.get(L)??{count:0,rescueBytes:0};X.count+=T.cnt??0,m.set(L,X)}}catch{}try{let j=R.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(j?.bytes&&(u+=j.bytes),j?.n&&(d+=j.n),j?.lastSec){let T=parseInt(j.lastSec,10)*1e3;if(Number.isFinite(T)&&T>f&&(f=T),Number.isFinite(T)&&(j?.bytes??0)>0){let C=h(T),L=m.get(C)??{count:0,rescueBytes:0};L.rescueBytes=Math.max(L.rescueBytes,j.bytes),m.set(C,L)}}}catch{}}finally{R.close()}}catch{}k&&c++}let g=l<p?(p-l)/864e5:0,_=Object.entries(i).filter(([,y])=>y>0).map(([y,x])=>({category:y,count:x,label:Wu[y]||y})).sort((y,x)=>x.count-y.count),v=[...m.entries()].sort((y,x)=>y[0]-x[0]).map(([y,x])=>({ms:y,count:x.count,...x.rescueBytes>0?{rescueBytes:x.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:_,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:p>0?p:0,lastRescueMs:f>0?f:void 0,byDay:v}}function Sy(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,totalSavedTokens:0},r=t.sessionsDir??Dt(Ju(),".claude","context-mode","sessions");if(!fs(r))return e;let n=[];try{n=ko(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():Pt()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let d of n){let l=Dt(r,d);try{let p=new s(l,{readonly:!0});try{if(t.sessionId){let f=p.prepare(`SELECT
520
+ `,$);P>=0&&(R=P+2),j>=0&&($=j);let T=h.slice(R,$).trim();o.push({title:`[auto-memory] ${f.label}`,content:T,source:f.label,origin:"auto-memory",timestamp:m.mtime.toISOString()});break}}}catch(m){n$&&process.stderr.write(`[ctx] auto-memory file read failed: ${m}
521
+ `)}}return o.slice(0,e)}function s$(t,e){return e?wF(e)||!t?e:ea(t,e):t??""}var n$,i$=b(()=>{"use strict";Yr();n$=process.env.DEBUG?.includes("context-mode")});function a$(t){let{query:e,limit:r,store:n,sort:s="relevance",source:o,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:d}=t,l=[],p=new Date().toISOString();try{let f=n.searchWithFallback(e,r,o,i);l.push(...f.map(m=>({title:m.title,content:m.content,source:m.source,origin:"current-session",timestamp:m.timestamp||p,rank:m.rank,matchLayer:m.matchLayer,highlighted:m.highlighted,contentType:m.contentType})))}catch(f){by&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
522
+ `)}if(s==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",o);l.push(...f.map(m=>({title:`[${m.category}] ${m.type}`,content:m.data,source:"prior-session",origin:"prior-session",timestamp:m.created_at})))}}catch(f){by&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
523
+ `)}try{let f=o$([e],r,c,u,d);l.push(...f)}catch(f){by&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
524
+ `)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((f,m)=>(f.timestamp||"").localeCompare(m.timestamp||"")),l.slice(0,r)}var by,c$=b(()=>{"use strict";i$();by=process.env.DEBUG?.includes("context-mode")});import*as Rt from"node:fs";import*as ky from"node:path";function Sy(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function TF(t){if(!Rt.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Rt.readdirSync(t.projectsRoot)){let s=ky.join(t.projectsRoot,n),o;try{o=Rt.statSync(s)}catch{continue}if(!o.isDirectory())continue;let i;try{i=Rt.readdirSync(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=ky.join(s,a);try{let u=Rt.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e)try{let n=Rt.openSync(e,"r");try{let s=Buffer.alloc(8192),o=Rt.readSync(n,s,0,s.length,0),i=s.subarray(0,o).toString("utf-8");for(let a of i.split(`
525
+ `).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{Rt.closeSync(n)}}catch{}}function u$(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:s,strictPlatform:o}=t,i=o?[...Cd(o),...EF]:$F;for(let a of i){let c=e[a];if(c&&!Sy(c))return c}if(s){let a=TF({projectsRoot:s});if(a&&!Sy(a))return a}return n&&!Sy(n)?n:r}var EF,$F,l$=b(()=>{"use strict";An();EF=["CONTEXT_MODE_PROJECT_DIR"],$F=["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 PF}from"node:child_process";import{existsSync as hs,readdirSync as ko,statSync as RF}from"node:fs";import{homedir as Yu}from"node:os";import{join as Dt,sep as CF}from"node:path";function _$(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function IF(t){let e=t?.home??Yu();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,s])=>{let o=Dt(e,...s,"context-mode");return{name:n,sessionsDir:Dt(o,"sessions"),contentDir:Dt(o,"content")}})}function AF(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function ta(t){let e=Ze(),r=t?.sessionsDir??Dt(e,"context-mode","sessions"),n=t?.memoryRoot??Dt(e,"projects"),s=0,o=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(hs(r)){let f=[];try{f=ko(r).filter(m=>m.endsWith(".db"))}catch{}if(f.length>0){let m=null;try{m=t?.loadDatabase?t.loadDatabase():Pt()}catch{}if(m)for(let h of f){let g=Dt(r,h);try{let _=new m(g,{readonly:!0});try{let v=_.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),y=_.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=v?.cnt??0,o+=y?.cnt??0;try{let x=_.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let k of x)k.category&&(u[k.category]=(u[k.category]??0)+(k.cnt??0))}catch{}try{let x=_.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();x?.bytes&&(i+=x.bytes)}catch{}try{let x=_.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(x?.t){let k=x.t.endsWith("Z")?x.t:x.t+"Z",R=Date.parse(k);Number.isFinite(R)&&R<a&&(a=R)}}catch{}try{let x=_.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let k of x)k.p&&c.add(k.p)}catch{}}finally{_.close()}}catch{}}}}let d=0,l=0,p={};if(hs(n)){let f=[];try{f=ko(n).filter(m=>{try{return RF(Dt(n,m)).isDirectory()}catch{return!1}})}catch{}for(let m of f){let h=Dt(n,m,"memory");if(!hs(h))continue;let g=[];try{g=ko(h).filter(_=>_.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let _ of g){let v=AF(_);p[v]=(p[v]??0)+1}}}}return{totalEvents:s,totalSessions:o,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:p,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function x$(t){let e=t.sessionsDir??Dt(Yu(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!hs(e))return n;let s=[];try{s=ko(e).filter(y=>!(!y.endsWith(".db")||t.worktreeHash&&!y.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():Pt()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,p=0,f=0,m=new Map,h=y=>Math.floor(y/864e5)*864e5;for(let y of s){let x=Dt(e,y),k=!1;try{let R=new o(x,{readonly:!0});try{let $=R.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let j of $)j.category&&(i[j.category]=(i[j.category]??0)+(j.cnt??0),a+=j.cnt??0,k=!0);let P=R.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(P?.mn){let j=Date.parse(P.mn+(P.mn.endsWith("Z")?"":"Z"));Number.isFinite(j)&&j<l&&(l=j)}if(P?.mx){let j=Date.parse(P.mx+(P.mx.endsWith("Z")?"":"Z"));Number.isFinite(j)&&j>p&&(p=j)}try{let j=R.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let T of j){if(!T.sec)continue;let C=parseInt(T.sec,10)*1e3;if(!Number.isFinite(C))continue;let L=h(C),X=m.get(L)??{count:0,rescueBytes:0};X.count+=T.cnt??0,m.set(L,X)}}catch{}try{let j=R.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(j?.bytes&&(u+=j.bytes),j?.n&&(d+=j.n),j?.lastSec){let T=parseInt(j.lastSec,10)*1e3;if(Number.isFinite(T)&&T>f&&(f=T),Number.isFinite(T)&&(j?.bytes??0)>0){let C=h(T),L=m.get(C)??{count:0,rescueBytes:0};L.rescueBytes=Math.max(L.rescueBytes,j.bytes),m.set(C,L)}}}catch{}}finally{R.close()}}catch{}k&&c++}let g=l<p?(p-l)/864e5:0,_=Object.entries(i).filter(([,y])=>y>0).map(([y,x])=>({category:y,count:x,label:Gu[y]||y})).sort((y,x)=>x.count-y.count),v=[...m.entries()].sort((y,x)=>y[0]-x[0]).map(([y,x])=>({ms:y,count:x.count,...x.rescueBytes>0?{rescueBytes:x.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:_,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:p>0?p:0,lastRescueMs:f>0?f:void 0,byDay:v}}function wy(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,totalSavedTokens:0},r=t.sessionsDir??Dt(Yu(),".claude","context-mode","sessions");if(!hs(r))return e;let n=[];try{n=ko(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():Pt()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let d of n){let l=Dt(r,d);try{let p=new s(l,{readonly:!0});try{if(t.sessionId){let f=p.prepare(`SELECT
526
526
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
527
527
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
528
528
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
@@ -530,36 +530,36 @@ ${s}`}}var zE=b(()=>{"use strict"});import{execFileSync as sF}from"node:child_pr
530
530
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
531
531
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
532
532
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
533
- FROM session_events`).get();f&&(o+=Number(f.data_bytes??0),i+=Number(f.bytes_avoided??0),a+=Number(f.bytes_returned??0));try{let m=p.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();m?.bytes&&(c+=Number(m.bytes))}catch{}}}finally{p.close()}}catch{}}let u=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,totalSavedTokens:u}}function RF(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!fs(t.sessionsDir))return n;let s=[];try{s=ko(t.sessionsDir).filter(d=>d.endsWith(".db"))}catch{return n}if(s.length===0)return n;let o=null;try{o=e()}catch{return n}if(!o)return n;let i=new Set,a=new Set;for(let d of s){let l=Dt(t.sessionsDir,d);try{let p=new o(l,{readonly:!0});try{let f=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.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&&(n.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)&&h<n.firstMs&&(n.firstMs=h)}if(m?.mx){let h=Date.parse(m.mx+(m.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.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{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Yu(t){let e=$F({home:t?.home}),r=t?.loadDatabase??Pt,n={...PF,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!fs(c.sessionsDir))continue;let u=RF(c,r,n);s.push(u),o+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:o,totalSessions:i,totalBytes:a,perAdapter:s}}function Gu(t){return CF[t]??t}function rt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function OF(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function IF(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(!e){if(process.platform==="darwin")try{let n=SF("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-"))}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return{locale:e||"en-US",tz:r||"UTC"}}function l$(t){let e=Ju();return e?t===e?"~":t.startsWith(e+wF)?"~"+t.slice(e.length):t:t}function AF(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(h,g=2)=>h.toFixed(g),o=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),f=(e*.8/1e6).toFixed(2),m=[];return m.push(` $${s(n)} of Opus 4 tokens your team didn't burn.`),m.push(` context-mode kept ${rt(t)} out of context \u2014 that's ${o} months of Cursor Pro paid for itself.`),c>0&&u>0&&(m.push(""),m.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),m.push(""),m.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),m}function NF(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],p=e.events*h$,f=Math.round((e.snapshotBytes??0)/4),m=p+f,h=s?.conversation?.totalSavedTokens??0,g=Math.max(m,h),_=(r?.totalEvents??0)*h$,v=Math.round((r?.rescueBytes??0)/4),y=_+v,x=s?.lifetime?.totalSavedTokens??0,k=Math.max(y,x),R=Math.max(1,Math.round(k*.02)),$=n?.totalBytes&&n.totalBytes>0?n.totalBytes:k*4,P=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,j=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`,T=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,C=T>0?Math.max(1,Math.round((c-T)/864e5)):0,L=n?.totalSessions??r?.totalSessions??1,X=n?.perAdapter.filter(qe=>qe.isReal).length??0,ae;if(n&&X>=2)ae=`across ${X} AI tools`;else if(n&&X===1){let qe=n.perAdapter.find(Gr=>Gr.isReal);ae=`in ${qe?Gu(qe.name):"Claude Code"}`}else ae="in Claude Code";C>0?l.push(` Across ${C} days you ran ${hr(L)} conversations ${ae}.`):l.push(` You ran ${hr(L)} conversations ${ae}.`);let yt=C>0?$/C:0;l.push(` context-mode kept ${rt($)} out of your context window \u2014 about ${rt(yt)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let jt=e.firstEventMs&&e.firstEventMs>0?d$(e.firstEventMs,i,a):"";if(jt?l.push(` This conversation started ${jt} in ${l$(o)}.`):l.push(` This conversation lives in ${l$(o)}.`),l.push(` ${j}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let qe=e.lastRescueMs&&e.lastRescueMs>0?d$(e.lastRescueMs,i,a):"",Gr=Math.round(e.snapshotBytes/1024);qe?l.push(` On ${qe}, /compact fired \u2014 ${Gr} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${Gr} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let _t=Math.max(1,Math.round(g*.02)),_s=kn(g,g,32),ml=kn(_t,g,32),fl=g>0?(1-_t/g)*100:0;if(l.push(` Without context-mode ${rt(P).padStart(8)} ${_s} ${hr(g).padStart(7)} tokens`),l.push(` With context-mode ${rt(Math.max(1,Math.round(P*.02))).padStart(8)} ${ml} ${hr(_t).padStart(7)} tokens`),l.push(` ${fl.toFixed(0)}% kept out of context \xB7 your AI ran ${Math.max(1,Math.round(g/_t))}\xD7 longer before /compact fired`),l.push(""),e.byDay&&e.byDay.length>0){let qe=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${rt(P)} built up \u2014 ${qe} days, ${e.byDay.length} active:`),l.push(""),l.push(...MF(e.byDay,i,a))}l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),l.push("");let sT=e.byCategory.reduce((qe,Gr)=>qe+Gr.count,0).toLocaleString(i);l.push(` ${sT} things \u2014 files, errors, decisions, agent runs:`),l.push("");let oT=e.byCategory[0]?.count??1;for(let qe of e.byCategory)l.push(` ${qe.label.padEnd(26)} ${String(qe.count).padStart(5)} ${kn(qe.count,oT,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let Ly=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Fy=T>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(T)):"",Uy=r?.distinctProjects??0,iT=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${rt(P)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Ly?` \xB7 started ${Ly}`:""}.`),l.push(` All your work: ${rt($)} kept out \xB7 ${iT.toLocaleString(i)} captures across ${Uy} project${Uy===1?"":"s"}${Fy?` \xB7 since ${Fy}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...AF($,k,C)),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),l.push(""),r&&r.autoMemoryCount>0){l.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let qe=Object.entries(r.autoMemoryByPrefix).sort((ua,la)=>la[1]-ua[1]),Gr=qe.length>0?qe[0][1]:1;for(let[ua,la]of qe){let cT=x$[ua]??ua;l.push(` ${cT.padEnd(26)} ${String(la).padStart(2)} ${kn(la,Gr,20)}`)}}else l.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");l.push(""),l.push(""),l.push(" Your AI talks less, remembers more, costs less."),l.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),l.push("");let aT=u?`v${u}`:"context-mode";return l.push(` ${aT}`),u&&d&&d!=="unknown"&&y$(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),DF(l)}function DF(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function MF(t,e,r){if(t.length===0)return[];let n=[...t].sort((p,f)=>p.ms-f.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.ms),a=n[0];for(let p of n)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of n){let f=Math.round((p.ms-s.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[f]=m}let d=p=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,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}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let p of n){let f=d(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`:"";l.push(` ${f} ${m}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function d$(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),o=l=>s.find(p=>p.type===l)?.value??"",i=o("day"),a=o("month"),c=o("year"),u=o("hour"),d=o("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${d} (${r})`}function hr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Ku(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Xu).toFixed(2)}`}function kn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function p$(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,s=[];s.push("");let o=e?.multiAdapter,i=o?.perAdapter.filter(h=>h.isReal).length??0,a=o?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=o?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";s.push(` All your work${h} \xB7 ${hr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${hr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${hr(h)} sessions`,_=a*256+r;s.push(` ${hr(a)} events \xB7 ${g} \xB7 ~${Ku(_)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Wu[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let p=l.slice(0,n),f=p.length>0?p[0].count:1;for(let h of p)s.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${kn(h.count,f,30)}`);let m=Math.max(0,l.length-n);return m>0&&s.push(` ... ${m} more categor${m===1?"y":"ies"}`),s}function m$(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((s,o)=>o[1]-s[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[s,o]of r){let i=x$[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${kn(o,n,20)}`)}return e}function f$(t,e){let r=[],n=Ku(t),s=(e?.totalEvents??0)*256+t,o=Ku(s);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${o} lifetime`),r.push("\u2500".repeat(65)),r}function g$(t){if(!t)return[];let e=t.perAdapter.filter(s=>s.isReal),r=t.perAdapter.filter(s=>!s.isReal);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let s=16,o=10,i=10,a=16;n.push(` ${"Tool".padEnd(s)}${"Captures".padStart(o)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,d)=>d.dataBytes+d.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let d=u.dataBytes+u.rescueBytes,l=u.eventCount>0?hr(u.eventCount):"\u2014",p=rt(u.dataBytes),f=rt(d);n.push(` ${Gu(u.name).padEnd(s)}${l.padStart(o)}${p.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>Gu(o.name)).join(", ");n.push(` Skipped (${r.length}): ${s}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function Qu(t,e,r,n){let s=[],o=OF(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(R=>R.isReal).length??0;if(d&&l>0){let R=d.totalSessions||i?.totalSessions||0,$=i?.firstEventMs??0,P=$>0?Math.max(1,Math.round((Date.now()-$)/864e5)):0,j=P>0?`Across ${P} day${P===1?"":"s"} `:"",T=R>0?`you ran ${hr(R)} conversation${R===1?"":"s"} `:"you ran ",C;if(l>=2)C=`across ${l} AI tools`;else{let L=d.perAdapter.find(X=>X.isReal);C=`in ${L?Gu(L.name):"Claude Code"}`}s.push(`${j}${T}${C}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let R=IF(),$=n?.cwd??process.cwd(),P=n?.now??Date.now(),j=n?.locale??R.locale,T=n?.tz??R.tz;return s.push(...NF({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:$,locale:j,tz:T,now:P,version:e,latestVersion:r})),s.join(`
534
- `)}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,_=Math.round(p/4),v=f>0?Math.max(1,Math.round(h/Math.max(f,1))):0;if(p===0){s.push(`context-mode ${o} ${m} calls`),s.push(""),m===0?s.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):s.push(`${rt(f)} entered context | 0 tokens saved`),s.push(...p$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),s.push(...g$(d)),s.push(...m$(i)),s.push(...f$(0,i)),s.push("");let R=e?`v${e}`:"context-mode";return s.push(R),e&&r&&r!=="unknown"&&y$(r,e)&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
535
- `)}s.push(`${hr(_)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${o} \xB7 ~${Ku(_)} saved (Opus)`),s.push(""),s.push(`Without context-mode |${kn(h,h)}| ${rt(h)}`),s.push(`With context-mode |${kn(f,h)}| ${rt(f)}`),s.push(""),v>=2?s.push(`${rt(p)} kept out of your conversation \u2014 ${v}\xD7 longer sessions before compact.`):s.push(`${rt(p)} kept out of your conversation. Never entered context.`),s.push("");let y=[`${m} calls`];t.cache&&t.cache.hits>0&&y.push(`${t.cache.hits} cache hits (+${rt(t.cache.bytes_saved)})`),s.push(y.join(" \xB7 "));let x=t.savings.by_tool.filter(R=>R.calls>0);if(x.length>=2){s.push("");let R=x.map($=>{let P=$.context_kb*1024,j=g<100?P/(1-g/100):P,T=Math.max(0,j-P);return{...$,returnedBytes:P,estimatedSaved:T}}).sort(($,P)=>P.estimatedSaved-$.estimatedSaved);for(let $ of R){let P=$.tool.length>22?$.tool.slice(0,19)+"...":$.tool;s.push(` ${P.padEnd(22)} ${String($.calls).padStart(4)} calls ${rt($.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let R=a.filter($=>$.median_concurrency!=null&&($.max_concurrency??1)>1);if(R.length>0){s.push(""),s.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let $ of R){let P=$.tool_name.replace(/^mcp__.*?__/,"");s.push(` ${P.padEnd(22)} ${$.calls} batches \xB7 ${$.median_concurrency} typical, ${$.max_concurrency} peak`)}}}s.push(...p$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:_})),s.push(...g$(d)),s.push(...m$(i)),s.push(...f$(_,i)),s.push("");let k=e?`v${e}`:"context-mode";return s.push(k),e&&r&&r!=="unknown"&&r!==e&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
536
- `)}var Wu,EF,wo,PF,x$,CF,Xu,h$,v$=b(()=>{"use strict";ms();Yr();Wu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},EF={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"},wo=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,s=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:s}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let s of e){let o;try{o=JSON.parse(s.data)}catch{continue}let i=typeof o.tool_name=="string"?o.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,o.truncated!==!0&&o.params&&typeof o.params=="object"){let c=o.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[s,o]of r){let i=null,a=null;if(o.concurrencies.length>0){let c=[...o.concurrencies].sort((d,l)=>d-l),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:s,calls:o.calls,median_concurrency:i,max_concurrency:a})}return n.sort((s,o)=>o.calls-s.calls||s.tool_name.localeCompare(o.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",s=Object.values(e.bytesReturned).reduce((C,L)=>C+L,0),o=Object.values(e.calls).reduce((C,L)=>C+L,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+s,c=a/Math.max(s,1),u=a>0?Math.round((1-s/a)*100):0,d=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),l=Array.from(d).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;if(e.cacheHits>0||e.cacheBytesSaved>0){let C=a+e.cacheBytesSaved,L=C/Math.max(s,1),X=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));m={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:X,total_with_cache:C,total_savings_ratio:L}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),v=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,y=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),x=y?!y.consumed:!1,k=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),R=new Map;for(let C of k){R.has(C.category)||R.set(C.category,new Set);let L=R.get(C.category);if(L.size<5){let X=C.data;C.category==="file"?X=C.data.split("/").pop()||C.data:(C.category==="prompt"||C.category==="user-prompt")&&(X=X.length>50?X.slice(0,47)+"...":X),X.length>40&&(X=X.slice(0,37)+"..."),L.add(X)}}let $=g.map(C=>({category:C.category,count:C.cnt,label:Wu[C.category]||C.category,preview:R.get(C.category)?Array.from(R.get(C.category)).join(", "):"",why:EF[C.category]||"Survives context resets"})),P=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),T=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:Wu[C.category]||C.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(s/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:l,total_calls:o,total_bytes_returned:s,kept_out:i,total_processed:a},cache:m,session:{id:n,uptime_min:f},continuity:{total_events:h,by_category:$,compact_count:v,resume_ready:x},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:T}}}};PF={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};x$={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},CF={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};Xu=15/1e6;h$=256});var Z$={};Le(Z$,{browserOpenArgv:()=>H$,buildBatchNodeOptionsPrefix:()=>z$,buildFetchCode:()=>U$,classifyIp:()=>cl,extractSnippet:()=>Dy,formatBatchQueryResults:()=>j$,killProcessOnPort:()=>jy,openBrowserSync:()=>Ry,positionsFromHighlight:()=>M$,runBatchCommands:()=>L$});import{createRequire as O$}from"node:module";import{existsSync as ze,unlinkSync as ra,readdirSync as jF,readFileSync as Cy,writeFileSync as Oy,renameSync as zF,rmSync as nl,mkdirSync as na,cpSync as LF,statSync as b$,symlinkSync as FF,lstatSync as UF}from"node:fs";import{execSync as S$,spawnSync as I$}from"node:child_process";import{join as Ce,dirname as er,resolve as ut,sep as HF,isAbsolute as ZF}from"node:path";import{fileURLToPath as BF}from"node:url";import{homedir as al,tmpdir as Iy,cpus as qF}from"node:os";import{request as VF}from"node:https";function WF(t){try{let e=ct();if(!ze(e))return;let r=jF(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let s=Ce(e,n);try{t.index({path:s,source:"session-events"}),ra(s)}catch{}}}catch{}}function $y(){return Ze()}async function GF(){if(wn)return wn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(Os(),Ma)),e=sr();return await t(e.platform)}catch{return null}}function ct(){if(wn)return wn.getSessionDir();try{let e=sr(),r=Rd(e.platform);if(r){let n=Ce(al(),...r);r.length===1&&r[0]===".claude"?n=$y():r.length===1&&r[0]===".codex"&&(n=$a());let s=Ce(n,"context-mode","sessions");return na(s,{recursive:!0}),s}}catch{}let t=Ce($y(),"context-mode","sessions");return na(t,{recursive:!0}),t}function _r(){let t;try{sr().platform==="claude-code"&&(t=Ce(al(),".claude","projects"))}catch{}return c$({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:t})}function KF(t){return ZF(t)?t:ut(_r(),t)}function sa(){return qu({projectDir:_r(),sessionsDir:ct()})}function Ty(){let t=Ce(er(ct()),"content");return na(t,{recursive:!0}),qE({projectDir:_r(),contentDir:t})}function gs(){if(!gr){let t=Ty();gr=new Fu(t),gr.setDenyChecker(e=>{try{let r=_r(),n=ly("Read",r);return py(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=er(Ty());iy(e,14),gr.cleanupStaleSources(14);let r=Ce(al(),".context-mode","content");ze(r)&&iy(r,0)}catch{}oy()}return WF(gr),gr}async function w$(){return new Promise(t=>{let e=VF("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",s=>{n+=s}),r.on("end",()=>{try{let s=JSON.parse(n);t(s.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function XF(){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 QF(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function e2(){return!Vr||Vr==="unknown"?!1:QF(Vr,qr)}function t2(){if(!e2())return!1;let t=Date.now();if(el>=JF){if(t-k$<YF)return!1;el=0}return el===0&&(k$=t),el++,!0}function r2(){if(!E$){E$=!0;try{let t=Ze(),e=ut(t,"plugins","installed_plugins.json");if(!ze(e))return;let r=JSON.parse(Cy(e,"utf-8")),n=ut(t,"plugins","cache"),s=ze(ut(Mt,"package.json"))?Mt:er(Mt);for(let[o,i]of Object.entries(r.plugins??{}))if(o==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||ze(c)||!ut(c).startsWith(n+HF))continue;try{UF(c).isSymbolicLink()&&ra(c)}catch{}let u=er(c);ze(u)||na(u,{recursive:!0}),ze(s)&&FF(s,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function K(t,e){if(r2(),t2()&&e.content.length>0){let n=XF();e.content[0].text=`\u26A0\uFE0F context-mode v${qr} outdated \u2192 v${Vr} available. Upgrade: ${n}
533
+ FROM session_events`).get();f&&(o+=Number(f.data_bytes??0),i+=Number(f.bytes_avoided??0),a+=Number(f.bytes_returned??0));try{let m=p.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();m?.bytes&&(c+=Number(m.bytes))}catch{}}}finally{p.close()}}catch{}}let u=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,totalSavedTokens:u}}function DF(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!hs(t.sessionsDir))return n;let s=[];try{s=ko(t.sessionsDir).filter(d=>d.endsWith(".db"))}catch{return n}if(s.length===0)return n;let o=null;try{o=e()}catch{return n}if(!o)return n;let i=new Set,a=new Set;for(let d of s){let l=Dt(t.sessionsDir,d);try{let p=new o(l,{readonly:!0});try{let f=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.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&&(n.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)&&h<n.firstMs&&(n.firstMs=h)}if(m?.mx){let h=Date.parse(m.mx+(m.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.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{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Xu(t){let e=IF({home:t?.home}),r=t?.loadDatabase??Pt,n={...NF,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!hs(c.sessionsDir))continue;let u=DF(c,r,n);s.push(u),o+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:o,totalSessions:i,totalBytes:a,perAdapter:s}}function Ku(t){return MF[t]??t}function rt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function jF(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function zF(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(!e){if(process.platform==="darwin")try{let n=PF("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-"))}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return{locale:e||"en-US",tz:r||"UTC"}}function d$(t){let e=Yu();return e?t===e?"~":t.startsWith(e+CF)?"~"+t.slice(e.length):t:t}function LF(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(h,g=2)=>h.toFixed(g),o=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),f=(e*.8/1e6).toFixed(2),m=[];return m.push(` $${s(n)} of Opus 4 tokens your team didn't burn.`),m.push(` context-mode kept ${rt(t)} out of context \u2014 that's ${o} months of Cursor Pro paid for itself.`),c>0&&u>0&&(m.push(""),m.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),m.push(""),m.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),m}function FF(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],p=e.events*g$,f=Math.round((e.snapshotBytes??0)/4),m=p+f,h=s?.conversation?.totalSavedTokens??0,g=Math.max(m,h),_=(r?.totalEvents??0)*g$,v=Math.round((r?.rescueBytes??0)/4),y=_+v,x=s?.lifetime?.totalSavedTokens??0,k=Math.max(y,x),R=Math.max(1,Math.round(k*.02)),$=n?.totalBytes&&n.totalBytes>0?n.totalBytes:k*4,P=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,j=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`,T=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,C=T>0?Math.max(1,Math.round((c-T)/864e5)):0,L=n?.totalSessions??r?.totalSessions??1,X=n?.perAdapter.filter(qe=>qe.isReal).length??0,ae;if(n&&X>=2)ae=`across ${X} AI tools`;else if(n&&X===1){let qe=n.perAdapter.find(Gr=>Gr.isReal);ae=`in ${qe?Ku(qe.name):"Claude Code"}`}else ae="in Claude Code";C>0?l.push(` Across ${C} days you ran ${hr(L)} conversations ${ae}.`):l.push(` You ran ${hr(L)} conversations ${ae}.`);let yt=C>0?$/C:0;l.push(` context-mode kept ${rt($)} out of your context window \u2014 about ${rt(yt)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let jt=e.firstEventMs&&e.firstEventMs>0?p$(e.firstEventMs,i,a):"";if(jt?l.push(` This conversation started ${jt} in ${d$(o)}.`):l.push(` This conversation lives in ${d$(o)}.`),l.push(` ${j}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let qe=e.lastRescueMs&&e.lastRescueMs>0?p$(e.lastRescueMs,i,a):"",Gr=Math.round(e.snapshotBytes/1024);qe?l.push(` On ${qe}, /compact fired \u2014 ${Gr} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${Gr} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let _t=Math.max(1,Math.round(g*.02)),xs=kn(g,g,32),fl=kn(_t,g,32),hl=g>0?(1-_t/g)*100:0;if(l.push(` Without context-mode ${rt(P).padStart(8)} ${xs} ${hr(g).padStart(7)} tokens`),l.push(` With context-mode ${rt(Math.max(1,Math.round(P*.02))).padStart(8)} ${fl} ${hr(_t).padStart(7)} tokens`),l.push(` ${hl.toFixed(0)}% kept out of context \xB7 your AI ran ${Math.max(1,Math.round(g/_t))}\xD7 longer before /compact fired`),l.push(""),e.byDay&&e.byDay.length>0){let qe=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${rt(P)} built up \u2014 ${qe} days, ${e.byDay.length} active:`),l.push(""),l.push(...HF(e.byDay,i,a))}l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),l.push("");let oT=e.byCategory.reduce((qe,Gr)=>qe+Gr.count,0).toLocaleString(i);l.push(` ${oT} things \u2014 files, errors, decisions, agent runs:`),l.push("");let iT=e.byCategory[0]?.count??1;for(let qe of e.byCategory)l.push(` ${qe.label.padEnd(26)} ${String(qe.count).padStart(5)} ${kn(qe.count,iT,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let Uy=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Hy=T>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(T)):"",Zy=r?.distinctProjects??0,aT=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${rt(P)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Uy?` \xB7 started ${Uy}`:""}.`),l.push(` All your work: ${rt($)} kept out \xB7 ${aT.toLocaleString(i)} captures across ${Zy} project${Zy===1?"":"s"}${Hy?` \xB7 since ${Hy}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...LF($,k,C)),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),l.push(""),r&&r.autoMemoryCount>0){l.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let qe=Object.entries(r.autoMemoryByPrefix).sort((la,da)=>da[1]-la[1]),Gr=qe.length>0?qe[0][1]:1;for(let[la,da]of qe){let uT=v$[la]??la;l.push(` ${uT.padEnd(26)} ${String(da).padStart(2)} ${kn(da,Gr,20)}`)}}else l.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");l.push(""),l.push(""),l.push(" Your AI talks less, remembers more, costs less."),l.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),l.push("");let cT=u?`v${u}`:"context-mode";return l.push(` ${cT}`),u&&d&&d!=="unknown"&&_$(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),UF(l)}function UF(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function HF(t,e,r){if(t.length===0)return[];let n=[...t].sort((p,f)=>p.ms-f.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.ms),a=n[0];for(let p of n)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of n){let f=Math.round((p.ms-s.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[f]=m}let d=p=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,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}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let p of n){let f=d(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`:"";l.push(` ${f} ${m}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function p$(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),o=l=>s.find(p=>p.type===l)?.value??"",i=o("day"),a=o("month"),c=o("year"),u=o("hour"),d=o("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${d} (${r})`}function hr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Ju(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Qu).toFixed(2)}`}function kn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function m$(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,s=[];s.push("");let o=e?.multiAdapter,i=o?.perAdapter.filter(h=>h.isReal).length??0,a=o?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=o?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";s.push(` All your work${h} \xB7 ${hr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${hr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${hr(h)} sessions`,_=a*256+r;s.push(` ${hr(a)} events \xB7 ${g} \xB7 ~${Ju(_)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Gu[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let p=l.slice(0,n),f=p.length>0?p[0].count:1;for(let h of p)s.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${kn(h.count,f,30)}`);let m=Math.max(0,l.length-n);return m>0&&s.push(` ... ${m} more categor${m===1?"y":"ies"}`),s}function f$(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((s,o)=>o[1]-s[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[s,o]of r){let i=v$[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${kn(o,n,20)}`)}return e}function h$(t,e){let r=[],n=Ju(t),s=(e?.totalEvents??0)*256+t,o=Ju(s);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${o} lifetime`),r.push("\u2500".repeat(65)),r}function y$(t){if(!t)return[];let e=t.perAdapter.filter(s=>s.isReal),r=t.perAdapter.filter(s=>!s.isReal);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let s=16,o=10,i=10,a=16;n.push(` ${"Tool".padEnd(s)}${"Captures".padStart(o)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,d)=>d.dataBytes+d.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let d=u.dataBytes+u.rescueBytes,l=u.eventCount>0?hr(u.eventCount):"\u2014",p=rt(u.dataBytes),f=rt(d);n.push(` ${Ku(u.name).padEnd(s)}${l.padStart(o)}${p.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>Ku(o.name)).join(", ");n.push(` Skipped (${r.length}): ${s}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function el(t,e,r,n){let s=[],o=jF(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(R=>R.isReal).length??0;if(d&&l>0){let R=d.totalSessions||i?.totalSessions||0,$=i?.firstEventMs??0,P=$>0?Math.max(1,Math.round((Date.now()-$)/864e5)):0,j=P>0?`Across ${P} day${P===1?"":"s"} `:"",T=R>0?`you ran ${hr(R)} conversation${R===1?"":"s"} `:"you ran ",C;if(l>=2)C=`across ${l} AI tools`;else{let L=d.perAdapter.find(X=>X.isReal);C=`in ${L?Ku(L.name):"Claude Code"}`}s.push(`${j}${T}${C}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let R=zF(),$=n?.cwd??process.cwd(),P=n?.now??Date.now(),j=n?.locale??R.locale,T=n?.tz??R.tz;return s.push(...FF({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:$,locale:j,tz:T,now:P,version:e,latestVersion:r})),s.join(`
534
+ `)}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,_=Math.round(p/4),v=f>0?Math.max(1,Math.round(h/Math.max(f,1))):0;if(p===0){s.push(`context-mode ${o} ${m} calls`),s.push(""),m===0?s.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):s.push(`${rt(f)} entered context | 0 tokens saved`),s.push(...m$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),s.push(...y$(d)),s.push(...f$(i)),s.push(...h$(0,i)),s.push("");let R=e?`v${e}`:"context-mode";return s.push(R),e&&r&&r!=="unknown"&&_$(r,e)&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
535
+ `)}s.push(`${hr(_)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${o} \xB7 ~${Ju(_)} saved (Opus)`),s.push(""),s.push(`Without context-mode |${kn(h,h)}| ${rt(h)}`),s.push(`With context-mode |${kn(f,h)}| ${rt(f)}`),s.push(""),v>=2?s.push(`${rt(p)} kept out of your conversation \u2014 ${v}\xD7 longer sessions before compact.`):s.push(`${rt(p)} kept out of your conversation. Never entered context.`),s.push("");let y=[`${m} calls`];t.cache&&t.cache.hits>0&&y.push(`${t.cache.hits} cache hits (+${rt(t.cache.bytes_saved)})`),s.push(y.join(" \xB7 "));let x=t.savings.by_tool.filter(R=>R.calls>0);if(x.length>=2){s.push("");let R=x.map($=>{let P=$.context_kb*1024,j=g<100?P/(1-g/100):P,T=Math.max(0,j-P);return{...$,returnedBytes:P,estimatedSaved:T}}).sort(($,P)=>P.estimatedSaved-$.estimatedSaved);for(let $ of R){let P=$.tool.length>22?$.tool.slice(0,19)+"...":$.tool;s.push(` ${P.padEnd(22)} ${String($.calls).padStart(4)} calls ${rt($.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let R=a.filter($=>$.median_concurrency!=null&&($.max_concurrency??1)>1);if(R.length>0){s.push(""),s.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let $ of R){let P=$.tool_name.replace(/^mcp__.*?__/,"");s.push(` ${P.padEnd(22)} ${$.calls} batches \xB7 ${$.median_concurrency} typical, ${$.max_concurrency} peak`)}}}s.push(...m$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:_})),s.push(...y$(d)),s.push(...f$(i)),s.push(...h$(_,i)),s.push("");let k=e?`v${e}`:"context-mode";return s.push(k),e&&r&&r!=="unknown"&&r!==e&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
536
+ `)}var Gu,OF,wo,NF,v$,MF,Qu,g$,b$=b(()=>{"use strict";fs();Yr();Gu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},OF={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"},wo=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,s=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:s}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let s of e){let o;try{o=JSON.parse(s.data)}catch{continue}let i=typeof o.tool_name=="string"?o.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,o.truncated!==!0&&o.params&&typeof o.params=="object"){let c=o.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[s,o]of r){let i=null,a=null;if(o.concurrencies.length>0){let c=[...o.concurrencies].sort((d,l)=>d-l),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:s,calls:o.calls,median_concurrency:i,max_concurrency:a})}return n.sort((s,o)=>o.calls-s.calls||s.tool_name.localeCompare(o.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",s=Object.values(e.bytesReturned).reduce((C,L)=>C+L,0),o=Object.values(e.calls).reduce((C,L)=>C+L,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+s,c=a/Math.max(s,1),u=a>0?Math.round((1-s/a)*100):0,d=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),l=Array.from(d).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;if(e.cacheHits>0||e.cacheBytesSaved>0){let C=a+e.cacheBytesSaved,L=C/Math.max(s,1),X=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));m={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:X,total_with_cache:C,total_savings_ratio:L}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),v=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,y=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),x=y?!y.consumed:!1,k=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),R=new Map;for(let C of k){R.has(C.category)||R.set(C.category,new Set);let L=R.get(C.category);if(L.size<5){let X=C.data;C.category==="file"?X=C.data.split("/").pop()||C.data:(C.category==="prompt"||C.category==="user-prompt")&&(X=X.length>50?X.slice(0,47)+"...":X),X.length>40&&(X=X.slice(0,37)+"..."),L.add(X)}}let $=g.map(C=>({category:C.category,count:C.cnt,label:Gu[C.category]||C.category,preview:R.get(C.category)?Array.from(R.get(C.category)).join(", "):"",why:OF[C.category]||"Survives context resets"})),P=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),T=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:Gu[C.category]||C.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(s/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:l,total_calls:o,total_bytes_returned:s,kept_out:i,total_processed:a},cache:m,session:{id:n,uptime_min:f},continuity:{total_events:h,by_category:$,compact_count:v,resume_ready:x},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:T}}}};NF={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};v$={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},MF={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};Qu=15/1e6;g$=256});var B$={};Le(B$,{browserOpenArgv:()=>Z$,buildBatchNodeOptionsPrefix:()=>L$,buildFetchCode:()=>H$,classifyIp:()=>ul,extractSnippet:()=>jy,formatBatchQueryResults:()=>z$,killProcessOnPort:()=>Ly,openBrowserSync:()=>Oy,positionsFromHighlight:()=>j$,runBatchCommands:()=>F$});import{createRequire as I$}from"node:module";import{existsSync as ze,unlinkSync as na,readdirSync as ZF,readFileSync as Iy,writeFileSync as Ay,renameSync as BF,rmSync as sl,mkdirSync as sa,cpSync as qF,statSync as S$,symlinkSync as VF,lstatSync as WF}from"node:fs";import{execSync as k$,spawnSync as A$}from"node:child_process";import{join as Ce,dirname as er,resolve as ut,sep as GF,isAbsolute as KF}from"node:path";import{fileURLToPath as JF}from"node:url";import{homedir as cl,tmpdir as Ny,cpus as YF}from"node:os";import{request as XF}from"node:https";function QF(t){try{let e=ct();if(!ze(e))return;let r=ZF(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let s=Ce(e,n);try{t.index({path:s,source:"session-events"}),na(s)}catch{}}}catch{}}function Py(){return Ze()}async function e2(){if(wn)return wn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(An(),ja)),e=sr();return await t(e.platform)}catch{return null}}function ct(){if(wn)return wn.getSessionDir();try{let e=sr(),r=Od(e.platform);if(r){let n=Ce(cl(),...r);r.length===1&&r[0]===".claude"?n=Py():r.length===1&&r[0]===".codex"&&(n=Ta());let s=Ce(n,"context-mode","sessions");return sa(s,{recursive:!0}),s}}catch{}let t=Ce(Py(),"context-mode","sessions");return sa(t,{recursive:!0}),t}function _r(){let t,e;try{let r=sr().platform;e=r,r==="claude-code"&&(t=Ce(cl(),".claude","projects"))}catch{}return u$({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:t,strictPlatform:e})}function t2(t){return KF(t)?t:ut(_r(),t)}function oa(){return Vu({projectDir:_r(),sessionsDir:ct()})}function Ry(){let t=Ce(er(ct()),"content");return sa(t,{recursive:!0}),VE({projectDir:_r(),contentDir:t})}function ys(){if(!gr){let t=Ry();gr=new Uu(t),gr.setDenyChecker(e=>{try{let r=_r(),n=py("Read",r);return fy(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=er(Ry());cy(e,14),gr.cleanupStaleSources(14);let r=Ce(cl(),".context-mode","content");ze(r)&&cy(r,0)}catch{}ay()}return QF(gr),gr}async function E$(){return new Promise(t=>{let e=XF("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",s=>{n+=s}),r.on("end",()=>{try{let s=JSON.parse(n);t(s.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function s2(){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 o2(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function i2(){return!Vr||Vr==="unknown"?!1:o2(Vr,qr)}function a2(){if(!i2())return!1;let t=Date.now();if(tl>=r2){if(t-w$<n2)return!1;tl=0}return tl===0&&(w$=t),tl++,!0}function c2(){if(!$$){$$=!0;try{let t=Ze(),e=ut(t,"plugins","installed_plugins.json");if(!ze(e))return;let r=JSON.parse(Iy(e,"utf-8")),n=ut(t,"plugins","cache"),s=ze(ut(Mt,"package.json"))?Mt:er(Mt);for(let[o,i]of Object.entries(r.plugins??{}))if(o==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||ze(c)||!ut(c).startsWith(n+GF))continue;try{WF(c).isSymbolicLink()&&na(c)}catch{}let u=er(c);ze(u)||sa(u,{recursive:!0}),ze(s)&&VF(s,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function K(t,e){if(c2(),a2()&&e.content.length>0){let n=s2();e.content[0].text=`\u26A0\uFE0F context-mode v${qr} outdated \u2192 v${Vr} available. Upgrade: ${n}
537
537
 
538
- `+e.content[0].text}let r=e.content.reduce((n,s)=>n+Buffer.byteLength(s.text),0);return oe.calls[t]=(oe.calls[t]||0)+1,oe.bytesReturned[t]=(oe.bytesReturned[t]||0)+r,sl(),setImmediate(()=>QE(sa(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>GE({sessionDbPath:sa(),toolName:t,bytesReturned:r})),e}function yr(t,e="unknown"){oe.bytesIndexed+=t,sl(),t>0&&setImmediate(()=>KE({sessionDbPath:sa(),source:e,bytesAvoided:t}))}function A$(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`;return Ce(ct(),`stats-${t}.json`)}function sl(){let t=Date.now();if(!(t-Py<n2)){Py=t;try{let e=Object.values(oe.bytesReturned).reduce((l,p)=>l+p,0),r=Object.values(oe.calls).reduce((l,p)=>l+p,0),n=oe.bytesIndexed+oe.bytesSandboxed+oe.cacheBytesSaved,s=n+e,o=s>0?Math.round((1-e/s)*100):0,i=Math.round(n/4),a=tl?.tokens??0;if(!tl||t-tl.computedAt>o2)try{a=(ea({sessionsDir:ct()})?.totalEvents??0)*i2,tl={tokens:a,computedAt:t}}catch{}let c={schemaVersion:s2,version:qr,updated_at:t,session_start:oe.sessionStart,uptime_ms:t-oe.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:oe.bytesIndexed,bytes_sandboxed:oe.bytesSandboxed,cache_hits:oe.cacheHits,cache_bytes_saved:oe.cacheBytesSaved,kept_out:n,total_processed:s,reduction_pct:o,tokens_saved:i,dollars_saved_session:+(i*Xu).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Xu).toFixed(2),by_tool:Object.fromEntries(Object.keys({...oe.calls,...oe.bytesReturned}).map(l=>[l,{calls:oe.calls[l]||0,bytes:oe.bytesReturned[l]||0}]))},u=A$(),d=`${u}.tmp`;Oy(d,JSON.stringify(c)),zF(d,u)}catch{}}}function Ny(t,e){try{let r=uy(process.env.CLAUDE_PROJECT_DIR),n=dy(t,r);if(n.decision==="deny")return K(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function N$(t,e,r){try{let n=ME(t,e);if(n.length===0)return null;let s=uy(process.env.CLAUDE_PROJECT_DIR);for(let o of n){let i=dy(o,s);if(i.decision==="deny")return K(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${o}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function D$(t,e){try{let r=_r(),n=ly("Read",r),s=py(t,n,process.platform==="win32",r);if(s.denied)return K(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${s.matchedPattern}`}],isError:!0})}catch{}return null}function M$(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===u2){for(e.push(r),n++;n<t.length&&t[n]!==l2;)r++,n++;n<t.length&&n++}else r++,n++;return e}function Dy(t,e,r=1500,n){if(t.length<=r)return t;let s=[];if(n)for(let u of M$(n))s.push(u);if(s.length===0){let u=e.toLowerCase().split(/\s+/).filter(l=>l.length>2),d=t.toLowerCase();for(let l of u){let p=d.indexOf(l);for(;p!==-1;)s.push(p),p=d.indexOf(l,p+1)}}if(s.length===0)return t.slice(0,r)+`
538
+ `+e.content[0].text}let r=e.content.reduce((n,s)=>n+Buffer.byteLength(s.text),0);return oe.calls[t]=(oe.calls[t]||0)+1,oe.bytesReturned[t]=(oe.bytesReturned[t]||0)+r,ol(),setImmediate(()=>e$(oa(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>KE({sessionDbPath:oa(),toolName:t,bytesReturned:r})),e}function yr(t,e="unknown"){oe.bytesIndexed+=t,ol(),t>0&&setImmediate(()=>JE({sessionDbPath:oa(),source:e,bytesAvoided:t}))}function N$(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`;return Ce(ct(),`stats-${t}.json`)}function ol(){let t=Date.now();if(!(t-Cy<u2)){Cy=t;try{let e=Object.values(oe.bytesReturned).reduce((l,p)=>l+p,0),r=Object.values(oe.calls).reduce((l,p)=>l+p,0),n=oe.bytesIndexed+oe.bytesSandboxed+oe.cacheBytesSaved,s=n+e,o=s>0?Math.round((1-e/s)*100):0,i=Math.round(n/4),a=rl?.tokens??0;if(!rl||t-rl.computedAt>d2)try{a=(ta({sessionsDir:ct()})?.totalEvents??0)*p2,rl={tokens:a,computedAt:t}}catch{}let c={schemaVersion:l2,version:qr,updated_at:t,session_start:oe.sessionStart,uptime_ms:t-oe.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:oe.bytesIndexed,bytes_sandboxed:oe.bytesSandboxed,cache_hits:oe.cacheHits,cache_bytes_saved:oe.cacheBytesSaved,kept_out:n,total_processed:s,reduction_pct:o,tokens_saved:i,dollars_saved_session:+(i*Qu).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Qu).toFixed(2),by_tool:Object.fromEntries(Object.keys({...oe.calls,...oe.bytesReturned}).map(l=>[l,{calls:oe.calls[l]||0,bytes:oe.bytesReturned[l]||0}]))},u=N$(),d=`${u}.tmp`;Ay(d,JSON.stringify(c)),BF(d,u)}catch{}}}function My(t,e){try{let r=dy(process.env.CLAUDE_PROJECT_DIR),n=my(t,r);if(n.decision==="deny")return K(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function D$(t,e,r){try{let n=jE(t,e);if(n.length===0)return null;let s=dy(process.env.CLAUDE_PROJECT_DIR);for(let o of n){let i=my(o,s);if(i.decision==="deny")return K(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${o}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function M$(t,e){try{let r=_r(),n=py("Read",r),s=fy(t,n,process.platform==="win32",r);if(s.denied)return K(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${s.matchedPattern}`}],isError:!0})}catch{}return null}function j$(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===h2){for(e.push(r),n++;n<t.length&&t[n]!==g2;)r++,n++;n<t.length&&n++}else r++,n++;return e}function jy(t,e,r=1500,n){if(t.length<=r)return t;let s=[];if(n)for(let u of j$(n))s.push(u);if(s.length===0){let u=e.toLowerCase().split(/\s+/).filter(l=>l.length>2),d=t.toLowerCase();for(let l of u){let p=d.indexOf(l);for(;p!==-1;)s.push(p),p=d.indexOf(l,p+1)}}if(s.length===0)return t.slice(0,r)+`
539
539
  \u2026`;s.sort((u,d)=>u-d);let o=300,i=[];for(let u of s){let d=Math.max(0,u-o),l=Math.min(t.length,u+o);i.length>0&&d<=i[i.length-1][1]?i[i.length-1][1]=l:i.push([d,l])}let a=[],c=0;for(let[u,d]of i){if(c>=r)break;let l=t.slice(u,Math.min(d,u+(r-c)));a.push((u>0?"\u2026":"")+l+(d<t.length?"\u2026":"")),c+=l.length}return a.join(`
540
540
 
541
- `)}function j$(t,e,r,n=80*1024){let s=[],o=0;for(let i of e){if(o>n){s.push(`## ${i}
541
+ `)}function z$(t,e,r,n=80*1024){let s=[],o=0;for(let i of e){if(o>n){s.push(`## ${i}
542
542
  (output cap reached \u2014 use ctx_search(queries: ["${i}"]) for details)
543
- `);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(s.push(`## ${i}`),s.push(""),a.length>0){for(let c of a){let u=Dy(c.content,i,3e3,c.highlighted);s.push(`### ${c.title}`),s.push(u),s.push(""),o+=u.length+c.title.length}continue}s.push("No matching sections found."),s.push("")}return s.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),s}function d2(t){return`'${t.replace(/'/g,"'\\''")}'`}function p2(t){return`'${t.replace(/'/g,"''")}'`}function z$(t,e){let r=`--require ${e}`,n=t.toLowerCase(),s=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${p2(r)}; `:s==="cmd"||s==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${d2(r)} `}function $$(t,e,r){let n=e||"(no output)",s=n.matchAll(/__CM_FS__:(\d+)/g),o=0;for(let i of s)o+=parseInt(i[1]);return o>0&&(r?.(o),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
543
+ `);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(s.push(`## ${i}`),s.push(""),a.length>0){for(let c of a){let u=jy(c.content,i,3e3,c.highlighted);s.push(`### ${c.title}`),s.push(u),s.push(""),o+=u.length+c.title.length}continue}s.push("No matching sections found."),s.push("")}return s.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),s}function y2(t){return`'${t.replace(/'/g,"'\\''")}'`}function _2(t){return`'${t.replace(/'/g,"''")}'`}function L$(t,e){let r=`--require ${e}`,n=t.toLowerCase(),s=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${_2(r)}; `:s==="cmd"||s==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${y2(r)} `}function T$(t,e,r){let n=e||"(no output)",s=n.matchAll(/__CM_FS__:(\d+)/g),o=0;for(let i of s)o+=parseInt(i[1]);return o>0&&(r?.(o),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
544
544
 
545
545
  ${n}
546
- `}async function L$(t,e,r){let{timeout:n,concurrency:s,nodeOptsPrefix:o,onFsBytes:i}=e;if(s<=1){let l=[],p=Date.now(),f=!1;for(let m=0;m<t.length;m++){let h=t[m],g;if(n!==void 0){let v=Date.now()-p,y=n-v;if(y<=0){l.push(`# ${h.label}
546
+ `}async function F$(t,e,r){let{timeout:n,concurrency:s,nodeOptsPrefix:o,onFsBytes:i}=e;if(s<=1){let l=[],p=Date.now(),f=!1;for(let m=0;m<t.length;m++){let h=t[m],g;if(n!==void 0){let v=Date.now()-p,y=n-v;if(y<=0){l.push(`# ${h.label}
547
547
 
548
548
  (skipped \u2014 batch timeout exceeded)
549
- `),f=!0;continue}g=y}let _=await r.execute({language:"shell",code:`${o}${h.command} 2>&1`,timeout:g});if(l.push($$(h.label,_.stdout,i)),_.timedOut){f=!0;for(let v=m+1;v<t.length;v++)l.push(`# ${t[v].label}
549
+ `),f=!0;continue}g=y}let _=await r.execute({language:"shell",code:`${o}${h.command} 2>&1`,timeout:g});if(l.push(T$(h.label,_.stdout,i)),_.timedOut){f=!0;for(let v=m+1;v<t.length;v++)l.push(`# ${t[v].label}
550
550
 
551
551
  (skipped \u2014 batch timeout exceeded)
552
- `);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let p=await r.execute({language:"shell",code:`${o}${l.command} 2>&1`,timeout:n}),f=$$(l.label,p.stdout,i);return{output:p.timedOut?f.replace(/\n$/,"")+`
552
+ `);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let p=await r.execute({language:"shell",code:`${o}${l.command} 2>&1`,timeout:n}),f=T$(l.label,p.stdout,i);return{output:p.timedOut?f.replace(/\n$/,"")+`
553
553
  (timed out after ${n??"?"}ms)
554
- `:f,timedOut:!!p.timedOut}}})),{settled:c}=await Qg(a,{concurrency:s}),u=new Array(t.length),d=!1;for(let l=0;l<c.length;l++){let p=c[l];if(p.status==="fulfilled")u[l]=p.value.output,p.value.timedOut&&(d=!0);else{let f=p.reason instanceof Error?p.reason.message:String(p.reason);u[l]=`# ${t[l].label}
554
+ `:f,timedOut:!!p.timedOut}}})),{settled:c}=await ty(a,{concurrency:s}),u=new Array(t.length),d=!1;for(let l=0;l<c.length;l++){let p=c[l];if(p.status==="fulfilled")u[l]=p.value.output,p.value.timedOut&&(d=!0);else{let f=p.reason instanceof Error?p.reason.message:String(p.reason);u[l]=`# ${t[l].label}
555
555
 
556
556
  (executor error: ${f})
557
- `}}return{outputs:u,timedOut:d}}function F$(t,e){let r=gs();yr(Buffer.byteLength(t));let n=r.index({content:t,source:e});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
557
+ `}}return{outputs:u,timedOut:d}}function U$(t,e){let r=ys();yr(Buffer.byteLength(t));let n=r.index({content:t,source:e});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
558
558
  Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function Eo(t,e,r,n=5){let s=t.split(`
559
- `).length,o=Buffer.byteLength(t),i=gs(),a=i.indexPlainText(t,r),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${s}-line output (${(o/1024).toFixed(1)}KB).`];return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to explore the indexed content."),l.join(`
559
+ `).length,o=Buffer.byteLength(t),i=ys(),a=i.indexPlainText(t,r),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${s}-line output (${(o/1024).toFixed(1)}KB).`];return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to explore the indexed content."),l.join(`
560
560
  `)}let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${s} lines, ${(o/1024).toFixed(1)}KB):`,""];for(let l of c){let p=l.content.split(`
561
561
  `)[0].slice(0,120);d.push(` - ${l.title}: ${p}`)}return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),d.join(`
562
- `)}function My(t){if(typeof t=="string")try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t}function f2(t){let e=My(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function h2(){return wy||(wy=O$(import.meta.url).resolve("turndown")),wy}function g2(){return Ey||(Ey=O$(import.meta.url).resolve("turndown-plugin-gfm")),Ey}function U$(t,e){let r=JSON.stringify(h2()),n=JSON.stringify(g2()),s=JSON.stringify(e),o=cl.toString(),i=process.env.CTX_FETCH_STRICT==="1";return`
562
+ `)}function zy(t){if(typeof t=="string")try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t}function v2(t){let e=zy(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function b2(){return $y||($y=I$(import.meta.url).resolve("turndown")),$y}function S2(){return Ty||(Ty=I$(import.meta.url).resolve("turndown-plugin-gfm")),Ty}function H$(t,e){let r=JSON.stringify(b2()),n=JSON.stringify(S2()),s=JSON.stringify(e),o=ul.toString(),i=process.env.CTX_FETCH_STRICT==="1";return`
563
563
  const TurndownService = require(${r});
564
564
  const { gfm } = require(${n});
565
565
  const fs = require('fs');
@@ -784,20 +784,20 @@ async function main() {
784
784
  emit('text', text);
785
785
  }
786
786
  main();
787
- `}async function _2(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),s=await n(e.hostname,{all:!0,verbatim:!0});for(let o of s){let i=cl(o.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${o.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${o.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${n instanceof Error?n.message:String(n)}`,reason:"exit"}}return null}function cl(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?cl(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let s=r.split(".").map(a=>parseInt(a,10));if(s.length!==4||s.some(a=>isNaN(a)||a<0||a>255))return"block";let[o,i]=s;return o===169&&i===254||o===0||o>=224?"block":o===127||o===10||o===172&&i>=16&&i<=31||o===192&&i===168?"private":"public"}async function x2(t,e,r){let n=await _2(t);if(n)return n;if(!r){let o=gs(),i=ay(e,t),a=o.getSourceMeta(i);if(a){let c=new Date(a.indexedAt+"Z"),u=Date.now()-c.getTime();if(u<y2){let d=Math.floor(u/36e5),l=Math.floor(u/(60*1e3)),p=d>0?`${d}h ago`:l>0?`${l}m ago`:"just now",f=a.chunkCount*1600;return{kind:"cached",label:a.label,chunkCount:a.chunkCount,estimatedBytes:f,ageStr:p}}}}let s=Ce(Iy(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let o=U$(t,s),i=await ia.execute({language:"javascript",code:o,timeout:3e4});if(i.exitCode!==0)return{kind:"fetch_error",url:t,error:i.stderr||i.stdout||"unknown error",reason:"exit"};let a=(i.stdout||"").trim(),c;try{c=Cy(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return c.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:c,header:a}}catch(o){return{kind:"fetch_error",url:t,error:o instanceof Error?o.message:String(o),reason:"throw"}}finally{try{nl(s)}catch{}}}function v2(t){let e=gs(),r=ay(t.source,t.url),n;t.header==="__CM_CT__:json"?n=e.indexJSON(t.markdown,r):t.header==="__CM_CT__:text"?n=e.indexPlainText(t.markdown,r):n=e.index({content:t.markdown,source:r}),yr(Buffer.byteLength(t.markdown));let s=t.markdown.length>R$?t.markdown.slice(0,R$)+`
787
+ `}async function w2(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),s=await n(e.hostname,{all:!0,verbatim:!0});for(let o of s){let i=ul(o.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${o.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${o.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${n instanceof Error?n.message:String(n)}`,reason:"exit"}}return null}function ul(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?ul(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let s=r.split(".").map(a=>parseInt(a,10));if(s.length!==4||s.some(a=>isNaN(a)||a<0||a>255))return"block";let[o,i]=s;return o===169&&i===254||o===0||o>=224?"block":o===127||o===10||o===172&&i>=16&&i<=31||o===192&&i===168?"private":"public"}async function E2(t,e,r){let n=await w2(t);if(n)return n;if(!r){let o=ys(),i=uy(e,t),a=o.getSourceMeta(i);if(a){let c=new Date(a.indexedAt+"Z"),u=Date.now()-c.getTime();if(u<k2){let d=Math.floor(u/36e5),l=Math.floor(u/(60*1e3)),p=d>0?`${d}h ago`:l>0?`${l}m ago`:"just now",f=a.chunkCount*1600;return{kind:"cached",label:a.label,chunkCount:a.chunkCount,estimatedBytes:f,ageStr:p}}}}let s=Ce(Ny(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let o=H$(t,s),i=await aa.execute({language:"javascript",code:o,timeout:3e4});if(i.exitCode!==0)return{kind:"fetch_error",url:t,error:i.stderr||i.stdout||"unknown error",reason:"exit"};let a=(i.stdout||"").trim(),c;try{c=Iy(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return c.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:c,header:a}}catch(o){return{kind:"fetch_error",url:t,error:o instanceof Error?o.message:String(o),reason:"throw"}}finally{try{sl(s)}catch{}}}function $2(t){let e=ys(),r=uy(t.source,t.url),n;t.header==="__CM_CT__:json"?n=e.indexJSON(t.markdown,r):t.header==="__CM_CT__:text"?n=e.indexPlainText(t.markdown,r):n=e.index({content:t.markdown,source:r}),yr(Buffer.byteLength(t.markdown));let s=t.markdown.length>C$?t.markdown.slice(0,C$)+`
788
788
 
789
- \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:n.label,totalChunks:n.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function C$(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function H$(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 Ry(t,e=process.platform,r=I$){let n=H$(t,e),s=[];for(let{cmd:o,args:i}of n)try{let a=r(o,i,{stdio:"ignore",timeout:ta});if(!a.error&&a.status===0)return{ok:!0,method:o};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;s.push(`${o}: ${c}`)}catch(a){s.push(`${o}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:s.join("; ")}}function jy(t,e=process.platform,r=I$){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let s=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ta});if(s.error)return n.errors.push(`netstat: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=`:${t}`,i=new Set;for(let a of s.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let d=u[0],l=u[1],p=u[2],f=u[u.length-1];d==="TCP"&&l.endsWith(o)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:ta});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let s=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ta});if(s.error)return n.errors.push(`lsof: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=s.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of o){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:ta});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(s){n.errors.push(s instanceof Error?s.message:String(s))}return n}async function b2(){let t=oy();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Iy():"/tmp",r=Ce(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{ia.cleanupBackgrounded(),gr&&gr.close();try{ra(Ay)}catch{}try{ra(r)}catch{}if(Br&&Br.pid&&!Br.killed)try{Br.kill("SIGTERM")}catch{}},s=async()=>{try{Py=0,sl()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),LE({onShutdown:()=>s()});let o=new Au;await Ke.connect(o);try{Oy(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(Os(),Ma)),c=Ke.server.getClientVersion(),u=i(c??void 0);wn=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=e$(sa());if(i){for(let[a,c]of Object.entries(i.calls))oe.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))oe.bytesReturned[a]=c;i.sessionStart>0&&(oe.sessionStart=i.sessionStart)}}catch{}w$().then(i=>{i!=="unknown"&&(Vr=i)}),setInterval(()=>{w$().then(i=>{i!=="unknown"&&(Vr=i)})},3600*1e3).unref(),setInterval(()=>sl(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${qr} running on stdio`),console.error(`Detected runtimes:
790
- ${xa(oa)}`),bs()||(console.error(`
791
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var Mt,qr,oa,rl,Ke,ia,Ay,gr,wn,Br,oe,Vr,el,k$,JF,YF,E$,n2,s2,o2,i2,Py,tl,a2,c2,u2,l2,ol,il,hs,ky,m2,T$,P$,wy,Ey,y2,R$,ta,B$=b(()=>{"use strict";rE();iE();Kg();Xg();yE();OE();IE();jE();ba();zE();FE();Yi();WE();YE();t$();a$();Xr();Os();ed();Ol();Yr();u$();ms();v$();rs();Mt=er(BF(import.meta.url)),qr=(()=>{for(let t of["../package.json","./package.json"]){let e=ut(Mt,t);if(ze(e))try{return JSON.parse(Cy(e,"utf8")).version}catch{}}return"unknown"})();process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
789
+ \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:n.label,totalChunks:n.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function O$(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function Z$(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 Oy(t,e=process.platform,r=A$){let n=Z$(t,e),s=[];for(let{cmd:o,args:i}of n)try{let a=r(o,i,{stdio:"ignore",timeout:ra});if(!a.error&&a.status===0)return{ok:!0,method:o};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;s.push(`${o}: ${c}`)}catch(a){s.push(`${o}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:s.join("; ")}}function Ly(t,e=process.platform,r=A$){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let s=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ra});if(s.error)return n.errors.push(`netstat: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=`:${t}`,i=new Set;for(let a of s.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let d=u[0],l=u[1],p=u[2],f=u[u.length-1];d==="TCP"&&l.endsWith(o)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:ra});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let s=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ra});if(s.error)return n.errors.push(`lsof: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=s.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of o){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:ra});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(s){n.errors.push(s instanceof Error?s.message:String(s))}return n}async function T2(){let t=ay();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Ny():"/tmp",r=Ce(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{aa.cleanupBackgrounded(),gr&&gr.close();try{na(Dy)}catch{}try{na(r)}catch{}if(Br&&Br.pid&&!Br.killed)try{Br.kill("SIGTERM")}catch{}},s=async()=>{try{Cy=0,ol()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),FE({onShutdown:()=>s()});let o=new Nu;await Ke.connect(o);try{Ay(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(An(),ja)),c=Ke.server.getClientVersion(),u=i(c??void 0);wn=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=t$(oa());if(i){for(let[a,c]of Object.entries(i.calls))oe.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))oe.bytesReturned[a]=c;i.sessionStart>0&&(oe.sessionStart=i.sessionStart)}}catch{}E$().then(i=>{i!=="unknown"&&(Vr=i)}),setInterval(()=>{E$().then(i=>{i!=="unknown"&&(Vr=i)})},3600*1e3).unref(),setInterval(()=>ol(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${qr} running on stdio`),console.error(`Detected runtimes:
790
+ ${va(ia)}`),Ss()||(console.error(`
791
+ Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var Mt,qr,ia,nl,Ke,aa,Dy,gr,wn,Br,oe,Vr,tl,w$,r2,n2,$$,u2,l2,d2,p2,Cy,rl,m2,f2,h2,g2,il,al,gs,Ey,x2,P$,R$,$y,Ty,k2,C$,ra,q$=b(()=>{"use strict";nE();aE();Yg();ey();_E();IE();AE();zE();Sa();LE();UE();Xi();GE();XE();r$();c$();Xr();An();td();Il();Yr();l$();fs();b$();ns();Mt=er(JF(import.meta.url)),qr=(()=>{for(let t of["../package.json","./package.json"]){let e=ut(Mt,t);if(ze(e))try{return JSON.parse(Iy(e,"utf8")).version}catch{}}return"unknown"})();process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
792
792
  `)});process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
793
- `)});oa=vs(),rl=va(oa),Ke=new Ou({name:"context-mode",version:qr});Ke.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ke.server.setRequestHandler(Js,async()=>({prompts:[]}));Ke.server.setRequestHandler(Gs,async()=>({resources:[]}));Ke.server.setRequestHandler(Ks,async()=>({resourceTemplates:[]}));ia=new yo({runtimes:oa,projectRoot:()=>_r()}),Ay=Ce(Iy(),`cm-fs-preload-${process.pid}.js`);Oy(Ay,`(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){}})();
794
- `);gr=null;wn=null,Br=null;oe={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()},Vr=null,el=0,k$=0,JF=3,YF=3600*1e3;E$=!1;n2=500,s2=2,o2=3e4,i2=256,Py=0;a2=rl.join(", "),c2=bs()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",u2="",l2="";Ke.registerTool("ctx_execute",{title:"Execute Code",description:`MANDATORY: Use for any command where output exceeds 20 lines. Execute code in a sandboxed subprocess. Only stdout enters context \u2014 raw data stays in the subprocess.${c2} Available: ${a2}.
793
+ `)});ia=bs(),nl=ba(ia),Ke=new Iu({name:"context-mode",version:qr});Ke.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ke.server.setRequestHandler(Js,async()=>({prompts:[]}));Ke.server.setRequestHandler(Gs,async()=>({resources:[]}));Ke.server.setRequestHandler(Ks,async()=>({resourceTemplates:[]}));aa=new yo({runtimes:ia,projectRoot:()=>_r()}),Dy=Ce(Ny(),`cm-fs-preload-${process.pid}.js`);Ay(Dy,`(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){}})();
794
+ `);gr=null;wn=null,Br=null;oe={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()},Vr=null,tl=0,w$=0,r2=3,n2=3600*1e3;$$=!1;u2=500,l2=2,d2=3e4,p2=256,Cy=0;m2=nl.join(", "),f2=Ss()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",h2="",g2="";Ke.registerTool("ctx_execute",{title:"Execute Code",description:`MANDATORY: Use for any command where output exceeds 20 lines. Execute code in a sandboxed subprocess. Only stdout enters context \u2014 raw data stays in the subprocess.${f2} Available: ${m2}.
795
795
 
796
796
  PREFER THIS OVER BASH for: API calls (gh, curl, aws), test runners (npm test, pytest), git queries (git log, git diff), data processing, and ANY CLI command that may produce large output. Bash should only be used for file mutations, git writes, and navigation.
797
797
 
798
798
  THINK IN CODE: When you need to analyze, count, filter, compare, or process data \u2014 write code that does the work and console.log() only the answer. Do NOT read raw data into context to process mentally. Program the analysis, don't compute it in your reasoning. Write robust, pure JavaScript (no npm dependencies). Use only Node.js built-ins (fs, path, child_process). Always wrap in try/catch. Handle null/undefined. Works on both Node.js and Bun.`,inputSchema:U.object({language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), or IO.puts (Elixir) to output a summary to context."),timeout:U.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:U.boolean().optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:U.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'.
799
799
 
800
- TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:s})=>{if(t==="shell"){let o=Ny(e,"execute");if(o)return o}else{let o=N$(e,t,"execute");if(o)return o}try{let o=e;(t==="javascript"||t==="typescript")&&(o=`
800
+ TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:s})=>{if(t==="shell"){let o=My(e,"execute");if(o)return o}else{let o=D$(e,t,"execute");if(o)return o}try{let o=e;(t==="javascript"||t==="typescript")&&(o=`
801
801
  // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
802
802
  let __cm_fs=0;
803
803
  process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
@@ -856,18 +856,18 @@ ${e}
856
856
  }
857
857
  __cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
858
858
  setInterval(()=>{},2147483647);`:""}
859
- })(typeof require!=='undefined'?require:null);`);let i=await ia.execute({language:t,code:o,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(oe.bytesSandboxed+=parseInt(a[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let c=i.stderr?.match(/__CM_FS__:(\d+)/);if(c&&(oe.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?K("ctx_execute",{content:[{type:"text",text:`${d}
859
+ })(typeof require!=='undefined'?require:null);`);let i=await aa.execute({language:t,code:o,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(oe.bytesSandboxed+=parseInt(a[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let c=i.stderr?.match(/__CM_FS__:(\d+)/);if(c&&(oe.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?K("ctx_execute",{content:[{type:"text",text:`${d}
860
860
 
861
861
  _(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?K("ctx_execute",{content:[{type:"text",text:`${d}
862
862
 
863
863
  _(timed out after ${r}ms \u2014 partial output shown above)_`}]}):K("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
864
864
 
865
865
  stderr:
866
- ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=my({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(l)>ol?(yr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:Eo(l,s,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>il?(yr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:Eo(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):K("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(u)>ol?(yr(Buffer.byteLength(u)),K("ctx_execute",{content:[{type:"text",text:Eo(u,s,`execute:${t}`)}]})):Buffer.byteLength(u)>il?K("ctx_execute",F$(u,`execute:${t}`)):K("ctx_execute",{content:[{type:"text",text:u}]})}catch(o){let i=o instanceof Error?o.message:String(o);return K("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});ol=5e3,il=102400;Ke.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file and process it without loading contents into context. The file is read into a FILE_CONTENT variable inside the sandbox. Only your printed summary enters context.
866
+ ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=hy({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(l)>il?(yr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:Eo(l,s,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>al?(yr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:Eo(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):K("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(u)>il?(yr(Buffer.byteLength(u)),K("ctx_execute",{content:[{type:"text",text:Eo(u,s,`execute:${t}`)}]})):Buffer.byteLength(u)>al?K("ctx_execute",U$(u,`execute:${t}`)):K("ctx_execute",{content:[{type:"text",text:u}]})}catch(o){let i=o instanceof Error?o.message:String(o);return K("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});il=5e3,al=102400;Ke.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file and process it without loading contents into context. The file is read into a FILE_CONTENT variable inside the sandbox. Only your printed summary enters context.
867
867
 
868
868
  PREFER THIS OVER Read/cat for: log files, data files (CSV, JSON, XML), large source files for analysis, and any file where you need to extract specific information rather than read the entire content.
869
869
 
870
- THINK IN CODE: Write code that processes FILE_CONTENT and console.log() only the answer. Don't read files into context to analyze mentally. Write robust, pure JavaScript \u2014 no npm deps, try/catch, null-safe. Node.js + Bun compatible.`,inputSchema:U.object({path:U.string().describe("Absolute file path or relative to project root"),language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts."),timeout:U.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:U.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:s})=>{let o=D$(t,"ctx_execute_file");if(o)return o;if(e==="shell"){let i=Ny(r,"execute_file");if(i)return i}else{let i=N$(r,e,"execute_file");if(i)return i}try{let i=await ia.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return K("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=my({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(u)>ol?(yr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:Eo(u,s,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>il?(yr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:Eo(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):K("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(a)>ol?(yr(Buffer.byteLength(a)),K("ctx_execute_file",{content:[{type:"text",text:Eo(a,s,`file:${t}`)}]})):Buffer.byteLength(a)>il?K("ctx_execute_file",F$(a,`file:${t}`)):K("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return K("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Ke.registerTool("ctx_index",{title:"Index Content",description:`Index documentation or knowledge content into a searchable BM25 knowledge base. Chunks markdown by headings (keeping code blocks intact) and stores in ephemeral FTS5 database. The full content does NOT stay in context \u2014 only a brief summary is returned.
870
+ THINK IN CODE: Write code that processes FILE_CONTENT and console.log() only the answer. Don't read files into context to analyze mentally. Write robust, pure JavaScript \u2014 no npm deps, try/catch, null-safe. Node.js + Bun compatible.`,inputSchema:U.object({path:U.string().describe("Absolute file path or relative to project root"),language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts."),timeout:U.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:U.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:s})=>{let o=M$(t,"ctx_execute_file");if(o)return o;if(e==="shell"){let i=My(r,"execute_file");if(i)return i}else{let i=D$(r,e,"execute_file");if(i)return i}try{let i=await aa.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return K("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=hy({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(u)>il?(yr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:Eo(u,s,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>al?(yr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:Eo(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):K("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(a)>il?(yr(Buffer.byteLength(a)),K("ctx_execute_file",{content:[{type:"text",text:Eo(a,s,`file:${t}`)}]})):Buffer.byteLength(a)>al?K("ctx_execute_file",U$(a,`file:${t}`)):K("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return K("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Ke.registerTool("ctx_index",{title:"Index Content",description:`Index documentation or knowledge content into a searchable BM25 knowledge base. Chunks markdown by headings (keeping code blocks intact) and stores in ephemeral FTS5 database. The full content does NOT stay in context \u2014 only a brief summary is returned.
871
871
 
872
872
  WHEN TO USE:
873
873
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
@@ -879,22 +879,22 @@ WHEN TO USE:
879
879
 
880
880
  After indexing, use 'ctx_search' to retrieve specific sections on-demand.
881
881
  When \`path\` is provided, a content hash is stored for automatic stale detection in search results.
882
- Do NOT use for: log files, test output, CSV, build output \u2014 use 'ctx_execute_file' for those.`,inputSchema:U.object({content:U.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:U.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:U.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')")})},async({content:t,path:e,source:r})=>{if(!t&&!e)return K("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=D$(e,"ctx_index");if(n)return n}try{let n=e?KF(e):void 0;if(t)yr(Buffer.byteLength(t));else if(n)try{let i=await import("fs");yr(i.readFileSync(n).byteLength)}catch{}let o=gs().index({content:t,path:n,source:r??n});return K("ctx_index",{content:[{type:"text",text:`Indexed ${o.totalChunks} sections (${o.codeChunks} with code) from: ${o.label}
883
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${o.label}" to scope results.`}]})}catch(n){let s=n instanceof Error?n.message:String(n);return K("ctx_index",{content:[{type:"text",text:`Index error: ${s}`}],isError:!0})}});hs=0,ky=Date.now(),m2=6e4,T$=3,P$=8;Ke.registerTool("ctx_search",{title:"Search Indexed Content",description:`Search indexed content. Requires prior indexing via ctx_batch_execute, ctx_index, or ctx_fetch_and_index. Pass ALL search questions as queries array in ONE call. File-backed sources are auto-refreshed when the source file changes.
882
+ Do NOT use for: log files, test output, CSV, build output \u2014 use 'ctx_execute_file' for those.`,inputSchema:U.object({content:U.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:U.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:U.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')")})},async({content:t,path:e,source:r})=>{if(!t&&!e)return K("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=M$(e,"ctx_index");if(n)return n}try{let n=e?t2(e):void 0;if(t)yr(Buffer.byteLength(t));else if(n)try{let i=await import("fs");yr(i.readFileSync(n).byteLength)}catch{}let o=ys().index({content:t,path:n,source:r??n});return K("ctx_index",{content:[{type:"text",text:`Indexed ${o.totalChunks} sections (${o.codeChunks} with code) from: ${o.label}
883
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${o.label}" to scope results.`}]})}catch(n){let s=n instanceof Error?n.message:String(n);return K("ctx_index",{content:[{type:"text",text:`Index error: ${s}`}],isError:!0})}});gs=0,Ey=Date.now(),x2=6e4,P$=3,R$=8;Ke.registerTool("ctx_search",{title:"Search Indexed Content",description:`Search indexed content. Requires prior indexing via ctx_batch_execute, ctx_index, or ctx_fetch_and_index. Pass ALL search questions as queries array in ONE call. File-backed sources are auto-refreshed when the source file changes.
884
884
 
885
885
  TIPS: 2-4 specific terms per query. Use 'source' to scope results.
886
886
 
887
- SESSION STATE: If skills, roles, or decisions were set earlier in this conversation, they are still active. Do not discard or contradict them.`,inputSchema:U.object({queries:U.preprocess(My,U.array(U.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:U.number().optional().default(3).describe("Results per query (default: 3)"),source:U.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:U.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:U.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory.")})},async t=>{try{let e=gs(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return K("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
887
+ SESSION STATE: If skills, roles, or decisions were set earlier in this conversation, they are still active. Do not discard or contradict them.`,inputSchema:U.object({queries:U.preprocess(zy,U.array(U.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:U.number().optional().default(3).describe("Results per query (default: 3)"),source:U.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:U.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:U.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory.")})},async t=>{try{let e=ys(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return K("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
888
888
 
889
889
  ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
890
890
  \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
891
891
  \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
892
892
  \u2022 ctx_index(content, source) \u2014 manually index text content
893
893
 
894
- After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,s=[];if(Array.isArray(n.queries)&&n.queries.length>0?s.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&s.push(n.query),s.length===0)return K("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:o=3,source:i,contentType:a}=t,c=Date.now();if(c-ky>m2&&(hs=0,ky=c),hs++,hs>P$)return K("ctx_search",{content:[{type:"text",text:`BLOCKED: ${hs} search calls in ${Math.round((c-ky)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let u=hs>T$?1:Math.min(o,2),d=40*1024,l=0,p=[],f=null;if(r==="timeline")try{let g=ct(),_=_r(),v=qu({projectDir:_,sessionsDir:g});ze(v)&&(f=new fr({dbPath:v}))}catch{}let m=wn?.getConfigDir()??$y();try{for(let g of s){if(l>d){p.push(`## ${g}
894
+ After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,s=[];if(Array.isArray(n.queries)&&n.queries.length>0?s.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&s.push(n.query),s.length===0)return K("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:o=3,source:i,contentType:a}=t,c=Date.now();if(c-Ey>x2&&(gs=0,Ey=c),gs++,gs>R$)return K("ctx_search",{content:[{type:"text",text:`BLOCKED: ${gs} search calls in ${Math.round((c-Ey)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let u=gs>P$?1:Math.min(o,2),d=40*1024,l=0,p=[],f=null;if(r==="timeline")try{let g=ct(),_=_r(),v=Vu({projectDir:_,sessionsDir:g});ze(v)&&(f=new fr({dbPath:v}))}catch{}let m=wn?.getConfigDir()??Py();try{for(let g of s){if(l>d){p.push(`## ${g}
895
895
  (output cap reached)
896
- `);continue}let _;if(r==="timeline"?_=i$({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:_r(),configDir:m,adapter:wn??void 0}):_=e.searchWithFallback(g,u,i,a),_.length===0){p.push(`## ${g}
897
- No results found.`);continue}let v=_.map((y,x)=>{let k=y.origin||"current-session",R=y.timestamp?y.timestamp.slice(0,16).replace("T"," "):"",$=`--- [${k}${R?" | "+R:""} | ${y.source}] ---`,P=`### ${y.title}`,j=Dy(y.content,g,1500,y.highlighted);return`${$}
896
+ `);continue}let _;if(r==="timeline"?_=a$({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:_r(),configDir:m,adapter:wn??void 0}):_=e.searchWithFallback(g,u,i,a),_.length===0){p.push(`## ${g}
897
+ No results found.`);continue}let v=_.map((y,x)=>{let k=y.origin||"current-session",R=y.timestamp?y.timestamp.slice(0,16).replace("T"," "):"",$=`--- [${k}${R?" | "+R:""} | ${y.source}] ---`,P=`### ${y.title}`,j=jy(y.content,g,1500,y.highlighted);return`${$}
898
898
  ${P}
899
899
 
900
900
  ${j}`}).join(`
@@ -907,10 +907,10 @@ ${v}`),l+=v.length}}finally{try{f?.close()}catch{}}let h=p.join(`
907
907
 
908
908
  `);if(e.lastRefreshCount>0&&(h=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
909
909
 
910
- `+h),hs>=T$&&(h+=`
910
+ `+h),gs>=P$&&(h+=`
911
911
 
912
- \u26A0 search call #${hs}/${P$} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),_=g.length>0?`
913
- Indexed sources: ${g.map(v=>`"${v.label}" (${v.chunkCount} sections)`).join(", ")}`:"";return K("ctx_search",{content:[{type:"text",text:`No results found.${_}`}]})}return K("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return K("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});wy=null,Ey=null;y2=1440*60*1e3,R$=3072;Ke.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown, indexes into searchable knowledge base, and returns a ~3KB preview. Full content stays in sandbox \u2014 use ctx_search() for deeper lookups.
912
+ \u26A0 search call #${gs}/${R$} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),_=g.length>0?`
913
+ Indexed sources: ${g.map(v=>`"${v.label}" (${v.chunkCount} sections)`).join(", ")}`:"";return K("ctx_search",{content:[{type:"text",text:`No results found.${_}`}]})}return K("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return K("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});$y=null,Ty=null;k2=1440*60*1e3,C$=3072;Ke.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown, indexes into searchable knowledge base, and returns a ~3KB preview. Full content stays in sandbox \u2014 use ctx_search() for deeper lookups.
914
914
 
915
915
  Better than WebFetch: preview is immediate, full content is searchable, raw HTML never enters context.
916
916
 
@@ -920,14 +920,14 @@ PARALLELIZE I/O: For multi-URL research (library evaluation, migration scans, do
920
920
  \u2705 Use concurrency: 4-8 for: library docs sweep, multi-changelog scan, competitive pricing pages, multi-region docs, GitHub raw file pulls.
921
921
  \u274C Single URL \u2192 use the legacy {url, source} shape (concurrency irrelevant).
922
922
  Example: requests: [{url: 'https://react.dev/...', source: 'react'}, {url: 'https://vuejs.org/...', source: 'vue'}], concurrency: 5.
923
- Fetches parallelize up to your concurrency setting; FTS5 indexing serializes the writes after (SQLite single-writer rule).`,inputSchema:U.object({url:U.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:U.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:U.array(U.object({url:U.string().describe("URL to fetch"),source:U.string().optional().describe("Label for this URL's indexed content")})).min(1).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:U.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:U.boolean().optional().describe("Skip cache and re-fetch even if content was recently indexed")})},async({url:t,source:e,requests:r,concurrency:n,force:s})=>{let o=r||(t?[{url:t,source:e}]:[]);if(o.length===0)return K("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(T=>({run:()=>x2(T.url,T.source,s)})),{settled:u,effectiveConcurrency:d,capped:l}=await Qg(c,{concurrency:a,capByCpuCount:!i&&a>1}),p=[];for(let T=0;T<u.length;T++){let C=u[T];if(C.status==="rejected"){let X=C.reason instanceof Error?C.reason.message:String(C.reason);p.push({kind:"job_error",url:o[T].url,error:X});continue}let L=C.value;if(L.kind==="cached"){oe.cacheHits++,oe.cacheBytesSaved+=L.estimatedBytes;let X=L.estimatedBytes,ae=L.label;setImmediate(()=>JE({sessionDbPath:sa(),source:ae,bytesAvoided:X})),p.push({kind:"cached",label:L.label,chunkCount:L.chunkCount,ageStr:L.ageStr})}else L.kind==="fetch_error"?p.push({kind:"fetch_error",url:L.url,error:L.error,reason:L.reason}):p.push({kind:"fetched",indexed:v2(L)})}if(i){let T=p[0];if(T.kind==="cached")return K("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${T.label}** \u2014 ${T.chunkCount} sections, indexed ${T.ageStr} (fresh, TTL: 24h).
923
+ Fetches parallelize up to your concurrency setting; FTS5 indexing serializes the writes after (SQLite single-writer rule).`,inputSchema:U.object({url:U.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:U.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:U.array(U.object({url:U.string().describe("URL to fetch"),source:U.string().optional().describe("Label for this URL's indexed content")})).min(1).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:U.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:U.boolean().optional().describe("Skip cache and re-fetch even if content was recently indexed")})},async({url:t,source:e,requests:r,concurrency:n,force:s})=>{let o=r||(t?[{url:t,source:e}]:[]);if(o.length===0)return K("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(T=>({run:()=>E2(T.url,T.source,s)})),{settled:u,effectiveConcurrency:d,capped:l}=await ty(c,{concurrency:a,capByCpuCount:!i&&a>1}),p=[];for(let T=0;T<u.length;T++){let C=u[T];if(C.status==="rejected"){let X=C.reason instanceof Error?C.reason.message:String(C.reason);p.push({kind:"job_error",url:o[T].url,error:X});continue}let L=C.value;if(L.kind==="cached"){oe.cacheHits++,oe.cacheBytesSaved+=L.estimatedBytes;let X=L.estimatedBytes,ae=L.label;setImmediate(()=>YE({sessionDbPath:oa(),source:ae,bytesAvoided:X})),p.push({kind:"cached",label:L.label,chunkCount:L.chunkCount,ageStr:L.ageStr})}else L.kind==="fetch_error"?p.push({kind:"fetch_error",url:L.url,error:L.error,reason:L.reason}):p.push({kind:"fetched",indexed:$2(L)})}if(i){let T=p[0];if(T.kind==="cached")return K("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${T.label}** \u2014 ${T.chunkCount} sections, indexed ${T.ageStr} (fresh, TTL: 24h).
924
924
  To refresh: call ctx_fetch_and_index again with \`force: true\`.
925
925
 
926
926
  You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
927
927
  Use: ctx_search(queries: [...], source: "${T.label}")`}]});if(T.kind==="fetched"){let C=(T.indexed.totalBytes/1024).toFixed(1),L=[`Fetched and indexed **${T.indexed.totalChunks} sections** (${C}KB) from: ${T.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${T.indexed.label}") for specific lookups.`,"","---","",T.indexed.preview].join(`
928
928
  `);return K("ctx_fetch_and_index",{content:[{type:"text",text:L}]})}if(T.kind==="fetch_error"){let C=T.reason==="empty"?`Fetched ${T.url} but got empty content`:T.reason==="read"?`Fetched ${T.url} but could not read subprocess output`:T.reason==="exit"?`Failed to fetch ${T.url}: ${T.error}`:`Fetch error: ${T.error}`;return K("ctx_fetch_and_index",{content:[{type:"text",text:C}],isError:!0})}return K("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${T.error}`}],isError:!0})}let f=384,m=[],h=0,g=0,_=0,v=0,y=0,x=[];for(let T of p)if(T.kind==="cached")_++,m.push(`- [cache] ${T.label} \u2014 ${T.chunkCount} sections (${T.ageStr})`);else if(T.kind==="fetched"){v++,h+=T.indexed.totalChunks,g+=T.indexed.totalBytes;let C=(T.indexed.totalBytes/1024).toFixed(1);m.push(`- [new] ${T.indexed.label} \u2014 ${T.indexed.totalChunks} sections (${C}KB)`);let L=T.indexed.preview.length>f?T.indexed.preview.slice(0,f).trimEnd()+"\u2026":T.indexed.preview;x.push(`### ${T.indexed.label}
929
929
 
930
- ${L}`)}else y++,m.push(`- [err] ${T.url}: ${T.error}`);let k=(g/1024).toFixed(1),R=l?` cap=${d}/${qF().length}cpu`:"",$=(T,C,L)=>`${T} ${T===1?C:L}`,j=[`fetched ${o.length} c=${d}${R}. ok=${v} cache=${_} err=${y}. ${$(h,"section","sections")} ${k}KB.`,"",...m,"",'ctx_search(queries: [...], source: "<label>") for full content.',...x.length>0?["","---","",...x]:[]].join(`
930
+ ${L}`)}else y++,m.push(`- [err] ${T.url}: ${T.error}`);let k=(g/1024).toFixed(1),R=l?` cap=${d}/${YF().length}cpu`:"",$=(T,C,L)=>`${T} ${T===1?C:L}`,j=[`fetched ${o.length} c=${d}${R}. ok=${v} cache=${_} err=${y}. ${$(h,"section","sections")} ${k}KB.`,"",...m,"",'ctx_search(queries: [...], source: "<label>") for full content.',...x.length>0?["","---","",...x]:[]].join(`
931
931
  `);return K("ctx_fetch_and_index",{content:[{type:"text",text:j}],isError:y===o.length})});Ke.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Execute multiple commands in ONE call, auto-index all output, and search with multiple queries. Returns search results directly \u2014 no follow-up calls needed.
932
932
 
933
933
  THIS IS THE PRIMARY TOOL. Use this instead of multiple ctx_execute() calls.
@@ -941,12 +941,12 @@ PARALLELIZE I/O: For I/O-bound batches (network calls, slow API queries, multi-U
941
941
  Example: [gh issue view 1, gh issue view 2, gh issue view 3] \u2192 concurrency: 3.
942
942
  Speedup depends on workload \u2014 applies to I/O wait, not CPU work.
943
943
 
944
- THINK IN CODE \u2014 NON-NEGOTIABLE: When commands produce data you need to analyze, count, filter, compare, or transform \u2014 add a processing command that runs JavaScript and console.log() ONLY the answer. NEVER pull raw output into context to reason over. Concurrency parallelizes the FETCH; THINK IN CODE owns the PROCESSING. One programmed analysis replaces ten read-and-reason rounds. Pure JavaScript, Node.js built-ins (fs, path, child_process), try/catch, null-safe.`,inputSchema:U.object({commands:U.preprocess(f2,U.array(U.object({label:U.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:U.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:U.preprocess(My,U.array(U.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:U.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:U.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let s of t){let o=Ny(s.command,"batch_execute");if(o)return o}try{let s=z$(oa.shell,Ay),{outputs:o,timedOut:i}=await L$(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:y=>{oe.bytesSandboxed+=y}},ia),a=o.join(`
944
+ THINK IN CODE \u2014 NON-NEGOTIABLE: When commands produce data you need to analyze, count, filter, compare, or transform \u2014 add a processing command that runs JavaScript and console.log() ONLY the answer. NEVER pull raw output into context to reason over. Concurrency parallelizes the FETCH; THINK IN CODE owns the PROCESSING. One programmed analysis replaces ten read-and-reason rounds. Pure JavaScript, Node.js built-ins (fs, path, child_process), try/catch, null-safe.`,inputSchema:U.object({commands:U.preprocess(v2,U.array(U.object({label:U.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:U.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:U.preprocess(zy,U.array(U.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:U.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:U.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let s of t){let o=My(s.command,"batch_execute");if(o)return o}try{let s=L$(ia.shell,Dy),{outputs:o,timedOut:i}=await F$(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:y=>{oe.bytesSandboxed+=y}},aa),a=o.join(`
945
945
  `),c=Buffer.byteLength(a),u=a.split(`
946
- `).length;if(i&&o.length===0)return K("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});yr(c);let d=gs(),l=`batch:${t.map(y=>y.label).join(",").slice(0,80)}`,p=d.index({content:a,source:l}),f=d.getChunksBySource(p.sourceId),m=["## Indexed Sections",""],h=[];for(let y of f){let x=Buffer.byteLength(y.content);m.push(`- ${y.title} (${(x/1024).toFixed(1)}KB)`),h.push(y.title)}let g=j$(d,e,l),_=d.getDistinctiveTerms?d.getDistinctiveTerms(p.sourceId):[],v=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${p.totalChunks} sections. Searched ${e.length} queries.`,"",...m,"",...g,_.length>0?`
946
+ `).length;if(i&&o.length===0)return K("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});yr(c);let d=ys(),l=`batch:${t.map(y=>y.label).join(",").slice(0,80)}`,p=d.index({content:a,source:l}),f=d.getChunksBySource(p.sourceId),m=["## Indexed Sections",""],h=[];for(let y of f){let x=Buffer.byteLength(y.content);m.push(`- ${y.title} (${(x/1024).toFixed(1)}KB)`),h.push(y.title)}let g=z$(d,e,l),_=d.getDistinctiveTerms?d.getDistinctiveTerms(p.sourceId):[],v=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${p.totalChunks} sections. Searched ${e.length} queries.`,"",...m,"",...g,_.length>0?`
947
947
  Searchable terms for follow-up: ${_.join(", ")}`:""].join(`
948
- `);return K("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(s){let o=s instanceof Error?s.message:String(s);return K("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${o}`}],isError:!0})}});Ke.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:U.object({})},async()=>{let t;try{let e=_r(),r=Zr(e),n=qu({projectDir:e,sessionsDir:ct()});if(ze(n)){let s=Pt(),o=new s(n,{readonly:!0});try{let i=new wo(o),a=i.queryAll(oe),c=i.getMcpToolUsage(),u=ea({sessionsDir:ct()}),d;try{d=Yu()}catch{}let l,p;try{let f=process.env.CLAUDE_SESSION_ID;if(f||(f=o.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),f){l=_$({sessionId:f,sessionsDir:ct(),worktreeHash:r});let m=Sy({sessionId:f,sessionsDir:ct(),worktreeHash:r}),h=Sy({sessionsDir:ct()});p={conversation:m,lifetime:h}}}catch{}t=Qu(a,qr,Vr,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:p,cwd:e})}finally{o.close()}}else{let o=new wo(C$()).queryAll(oe),i=ea({sessionsDir:ct()}),a;try{a=Yu()}catch{}t=Qu(o,qr,Vr,{lifetime:i,multiAdapter:a})}}catch{let r=new wo(C$()).queryAll(oe),n;try{n=ea({sessionsDir:ct()})}catch{}let s;try{s=Yu()}catch{}t=Qu(r,qr,Vr,n||s?{lifetime:n,multiAdapter:s}:void 0)}return K("ctx_stats",{content:[{type:"text",text:t}]})});Ke.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:U.object({})},async()=>{let t=["context-mode doctor",""],e=ze(ut(Mt,"package.json"))?Mt:er(Mt),r=11,n=(rl.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${rl.length}/${r} (${n}%) \u2014 ${rl.join(", ")}`),bs()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");{let o=new yo({runtimes:oa});try{let i=await o.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(i.exitCode===0&&i.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let a=i.stderr?.trim()?` (${i.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${i.exitCode}${a}`)}}catch(i){t.push(`[FAIL] Server test: FAIL \u2014 ${i instanceof Error?i.message:i}`)}finally{o.cleanupBackgrounded()}}{let o;try{let i=Pt();o=new i(":memory:"),o.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),o.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let a=o.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();a&&a.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(i){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${i instanceof Error?i.message:i}`)}finally{try{o?.close()}catch{}}}let s=await GF();if(s){for(let i of s.validateHooks(e)){let a=i.status==="pass"?"[OK]":i.status==="warn"?"[WARN]":"[FAIL]",c=i.fix?` \u2014 fix: ${i.fix}`:"";t.push(`${a} ${i.check}: ${i.message}${c}`)}let o=Sa(s,e);o.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let i of o){let a=ut(e,i);ze(a)?t.push(`[OK] Hook script: PASS \u2014 ${a}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${a}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${qr}`),K("ctx_doctor",{content:[{type:"text",text:t.join(`
949
- `)}]})});Ke.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:U.object({})},async()=>{let t=ze(ut(Mt,"package.json"))?Mt:er(Mt),e=ut(t,"cli.bundle.mjs"),r=ut(t,"build","cli.js");try{let i=ct(),a=Ce(er(i),"insight-cache");ze(a)&&(jy(4747),nl(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(Os(),Ma)),a=Ke.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let s;if(ze(e))s=`${Ue(e)} upgrade${n}`;else if(ze(r))s=`${Ue(r)} upgrade${n}`;else{let a=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync}from"node:fs";','import{join}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"for(const item of items){const from=join(T,item);const to=join(P,item);if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true});}}",'writeFileSync(join(P,".mcp.json"),JSON.stringify({mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}},null,2)+"\\n");','console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
948
+ `);return K("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(s){let o=s instanceof Error?s.message:String(s);return K("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${o}`}],isError:!0})}});Ke.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:U.object({})},async()=>{let t;try{let e=_r(),r=Zr(e),n=Vu({projectDir:e,sessionsDir:ct()});if(ze(n)){let s=Pt(),o=new s(n,{readonly:!0});try{let i=new wo(o),a=i.queryAll(oe),c=i.getMcpToolUsage(),u=ta({sessionsDir:ct()}),d;try{d=Xu()}catch{}let l,p;try{let f=process.env.CLAUDE_SESSION_ID;if(f||(f=o.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),f){l=x$({sessionId:f,sessionsDir:ct(),worktreeHash:r});let m=wy({sessionId:f,sessionsDir:ct(),worktreeHash:r}),h=wy({sessionsDir:ct()});p={conversation:m,lifetime:h}}}catch{}t=el(a,qr,Vr,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:p,cwd:e})}finally{o.close()}}else{let o=new wo(O$()).queryAll(oe),i=ta({sessionsDir:ct()}),a;try{a=Xu()}catch{}t=el(o,qr,Vr,{lifetime:i,multiAdapter:a})}}catch{let r=new wo(O$()).queryAll(oe),n;try{n=ta({sessionsDir:ct()})}catch{}let s;try{s=Xu()}catch{}t=el(r,qr,Vr,n||s?{lifetime:n,multiAdapter:s}:void 0)}return K("ctx_stats",{content:[{type:"text",text:t}]})});Ke.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:U.object({})},async()=>{let t=["context-mode doctor",""],e=ze(ut(Mt,"package.json"))?Mt:er(Mt),r=11,n=(nl.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${nl.length}/${r} (${n}%) \u2014 ${nl.join(", ")}`),Ss()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");{let o=new yo({runtimes:ia});try{let i=await o.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(i.exitCode===0&&i.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let a=i.stderr?.trim()?` (${i.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${i.exitCode}${a}`)}}catch(i){t.push(`[FAIL] Server test: FAIL \u2014 ${i instanceof Error?i.message:i}`)}finally{o.cleanupBackgrounded()}}{let o;try{let i=Pt();o=new i(":memory:"),o.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),o.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let a=o.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();a&&a.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(i){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${i instanceof Error?i.message:i}`)}finally{try{o?.close()}catch{}}}let s=await e2();if(s){for(let i of s.validateHooks(e)){let a=i.status==="pass"?"[OK]":i.status==="warn"?"[WARN]":"[FAIL]",c=i.fix?` \u2014 fix: ${i.fix}`:"";t.push(`${a} ${i.check}: ${i.message}${c}`)}let o=ka(s,e);o.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let i of o){let a=ut(e,i);ze(a)?t.push(`[OK] Hook script: PASS \u2014 ${a}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${a}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${qr}`),K("ctx_doctor",{content:[{type:"text",text:t.join(`
949
+ `)}]})});Ke.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:U.object({})},async()=>{let t=ze(ut(Mt,"package.json"))?Mt:er(Mt),e=ut(t,"cli.bundle.mjs"),r=ut(t,"build","cli.js");try{let i=ct(),a=Ce(er(i),"insight-cache");ze(a)&&(Ly(4747),sl(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(An(),ja)),a=Ke.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let s;if(ze(e))s=`${Ue(e)} upgrade${n}`;else if(ze(r))s=`${Ue(r)} upgrade${n}`;else{let a=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync}from"node:fs";','import{join}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"for(const item of items){const from=join(T,item);const to=join(P,item);if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true});}}",'writeFileSync(join(P,".mcp.json"),JSON.stringify({mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}},null,2)+"\\n");','console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
950
950
  `),c=ut(t,".ctx-upgrade-inline.mjs"),{writeFileSync:u}=await import("node:fs");u(c,a),s=Ue(c)}let o=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",s,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
951
951
  `);return K("ctx_upgrade",{content:[{type:"text",text:o}]})});Ke.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:`DESTRUCTIVE \u2014 permanently delete indexed content. CANNOT be undone.
952
952
 
@@ -970,43 +970,43 @@ REFUSAL RULES (tool returns an error):
970
970
 
971
971
  Use sessionId when the user asks to clear a specific conversation's data.
972
972
  Use scope:'project' ONLY when the user explicitly asks to reset everything.
973
- NEVER call with bare {confirm:true} \u2014 always specify the scope.`,inputSchema:U.object({confirm:U.boolean().describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:U.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:U.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")}).refine(t=>!(t.sessionId&&t.scope==="project"),{message:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe.",path:["scope"]})},async({confirm:t,sessionId:e,scope:r})=>{if(!t)return K("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let s;try{s=Ty()}catch{}if(gr){try{gr.cleanup()}catch{}gr=null}let o=s?er(s):void 0,{deleted:i}=VE({projectDir:_r(),sessionsDir:ct(),storePath:s,contentDir:o,legacyContentDir:Ce(al(),".context-mode","content"),contentHash:Hr(_r()),scope:n,sessionId:e});if(n==="project"){oe.calls={},oe.bytesReturned={},oe.bytesIndexed=0,oe.bytesSandboxed=0,oe.cacheHits=0,oe.cacheBytesSaved=0,oe.sessionStart=Date.now(),i.push("session stats");try{let c=A$();ze(c)&&ra(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return K("ctx_purge",{content:[{type:"text",text:a}]})});ta=5e3;Ke.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly.",inputSchema:U.object({port:U.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:U.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:U.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:U.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:U.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:s})=>{let o=t||4747,i=e||n,a=r||s,c=ze(ut(Mt,"package.json"))?Mt:er(Mt),u=ut(c,"insight"),d=i?ut(i):ct(),l=a?ut(a):Ce(er(d),"content"),p=Ce(er(d),"insight-cache");if(!ze(Ce(u,"server.mjs")))return K("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],m=!1;na(p,{recursive:!0});let h=b$(Ce(u,"server.mjs")).mtimeMs,g=ze(Ce(p,"server.mjs"))?b$(Ce(p,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),LF(u,p,{recursive:!0,force:!0}),f.push("Source files copied."),m=!0),!ze(Ce(p,"node_modules"))||m){f.push("Installing dependencies (first run, ~30s)...");try{S$(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:p,stdio:"pipe",timeout:3e5})}catch{try{nl(Ce(p,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!ze(Ce(p,"node_modules","vite"))||!ze(Ce(p,"node_modules","better-sqlite3")))throw nl(Ce(p,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),S$("npx vite build",{cwd:p,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let v=!1;try{let{request:P}=await import("node:http");await new Promise((j,T)=>{let C=P(`http://127.0.0.1:${o}/api/overview`,{timeout:2e3},L=>{L.resume(),j()});C.on("error",()=>T()),C.on("timeout",()=>{C.destroy(),T()}),C.end()}),v=!0}catch{}if(v&&m){f.push("Killing stale dashboard server (source updated)...");let P=jy(o);if(P.attemptedPids.length>0&&P.killedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Could not free port ${o} (kill failed for ${P.attemptedPids.join(", ")}: ${P.errors.join("; ")}). Try ctx_insight({ port: ${o+1} }) or stop the process manually.`}]});if(P.errors.length>0&&P.attemptedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${o}: ${P.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(j=>setTimeout(j,500)),f.push(`Stale server killed (${P.killedPids.length} pid${P.killedPids.length===1?"":"s"}).`)}else if(v){f.push("Dashboard already running.");let P=`http://localhost:${o}`,j=Ry(P),T=j.ok?"":` (auto-open failed: ${j.reason}; navigate manually)`;return K("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${P}${T}`}]})}if(Br&&Br.pid&&!Br.killed)try{Br.kill("SIGTERM")}catch{}let{spawn:y}=await import("node:child_process"),x=y("node",[Ce(p,"server.mjs")],{cwd:p,env:{...process.env,PORT:String(o),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});x.on("error",()=>{}),x.unref(),Br=x,await new Promise(P=>setTimeout(P,1500));try{let{request:P}=await import("node:http");await new Promise((j,T)=>{let C=P(`http://127.0.0.1:${o}/api/overview`,{timeout:3e3},L=>{j(),L.resume()});C.on("error",T),C.on("timeout",()=>{C.destroy(),T(new Error("timeout"))}),C.end()})}catch{return K("ctx_insight",{content:[{type:"text",text:`Port ${o} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
973
+ NEVER call with bare {confirm:true} \u2014 always specify the scope.`,inputSchema:U.object({confirm:U.boolean().describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:U.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:U.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")}).refine(t=>!(t.sessionId&&t.scope==="project"),{message:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe.",path:["scope"]})},async({confirm:t,sessionId:e,scope:r})=>{if(!t)return K("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let s;try{s=Ry()}catch{}if(gr){try{gr.cleanup()}catch{}gr=null}let o=s?er(s):void 0,{deleted:i}=WE({projectDir:_r(),sessionsDir:ct(),storePath:s,contentDir:o,legacyContentDir:Ce(cl(),".context-mode","content"),contentHash:Hr(_r()),scope:n,sessionId:e});if(n==="project"){oe.calls={},oe.bytesReturned={},oe.bytesIndexed=0,oe.bytesSandboxed=0,oe.cacheHits=0,oe.cacheBytesSaved=0,oe.sessionStart=Date.now(),i.push("session stats");try{let c=N$();ze(c)&&na(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return K("ctx_purge",{content:[{type:"text",text:a}]})});ra=5e3;Ke.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly.",inputSchema:U.object({port:U.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:U.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:U.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:U.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:U.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:s})=>{let o=t||4747,i=e||n,a=r||s,c=ze(ut(Mt,"package.json"))?Mt:er(Mt),u=ut(c,"insight"),d=i?ut(i):ct(),l=a?ut(a):Ce(er(d),"content"),p=Ce(er(d),"insight-cache");if(!ze(Ce(u,"server.mjs")))return K("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],m=!1;sa(p,{recursive:!0});let h=S$(Ce(u,"server.mjs")).mtimeMs,g=ze(Ce(p,"server.mjs"))?S$(Ce(p,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),qF(u,p,{recursive:!0,force:!0}),f.push("Source files copied."),m=!0),!ze(Ce(p,"node_modules"))||m){f.push("Installing dependencies (first run, ~30s)...");try{k$(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:p,stdio:"pipe",timeout:3e5})}catch{try{sl(Ce(p,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!ze(Ce(p,"node_modules","vite"))||!ze(Ce(p,"node_modules","better-sqlite3")))throw sl(Ce(p,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),k$("npx vite build",{cwd:p,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let v=!1;try{let{request:P}=await import("node:http");await new Promise((j,T)=>{let C=P(`http://127.0.0.1:${o}/api/overview`,{timeout:2e3},L=>{L.resume(),j()});C.on("error",()=>T()),C.on("timeout",()=>{C.destroy(),T()}),C.end()}),v=!0}catch{}if(v&&m){f.push("Killing stale dashboard server (source updated)...");let P=Ly(o);if(P.attemptedPids.length>0&&P.killedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Could not free port ${o} (kill failed for ${P.attemptedPids.join(", ")}: ${P.errors.join("; ")}). Try ctx_insight({ port: ${o+1} }) or stop the process manually.`}]});if(P.errors.length>0&&P.attemptedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${o}: ${P.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(j=>setTimeout(j,500)),f.push(`Stale server killed (${P.killedPids.length} pid${P.killedPids.length===1?"":"s"}).`)}else if(v){f.push("Dashboard already running.");let P=`http://localhost:${o}`,j=Oy(P),T=j.ok?"":` (auto-open failed: ${j.reason}; navigate manually)`;return K("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${P}${T}`}]})}if(Br&&Br.pid&&!Br.killed)try{Br.kill("SIGTERM")}catch{}let{spawn:y}=await import("node:child_process"),x=y("node",[Ce(p,"server.mjs")],{cwd:p,env:{...process.env,PORT:String(o),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});x.on("error",()=>{}),x.unref(),Br=x,await new Promise(P=>setTimeout(P,1500));try{let{request:P}=await import("node:http");await new Promise((j,T)=>{let C=P(`http://127.0.0.1:${o}/api/overview`,{timeout:3e3},L=>{j(),L.resume()});C.on("error",T),C.on("timeout",()=>{C.destroy(),T(new Error("timeout"))}),C.end()})}catch{return K("ctx_insight",{content:[{type:"text",text:`Port ${o} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
974
974
 
975
975
  To fix:
976
976
  - Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${o}`:`lsof -ti:${o} | xargs kill`}
977
- - Or use a different port: ctx_insight({ port: ${o+1} })`}]})}let k=`http://localhost:${o}`,R=Ry(k),$=R.ok?"":` (auto-open failed: ${R.reason}; navigate manually)`;return f.push(`Dashboard running at ${k}${$}`),K("ctx_insight",{content:[{type:"text",text:f.map(P=>`- ${P}`).join(`
977
+ - Or use a different port: ctx_insight({ port: ${o+1} })`}]})}let k=`http://localhost:${o}`,R=Oy(k),$=R.ok?"":` (auto-open failed: ${R.reason}; navigate manually)`;return f.push(`Dashboard running at ${k}${$}`),K("ctx_insight",{content:[{type:"text",text:f.map(P=>`- ${P}`).join(`
978
978
  `)+`
979
979
 
980
980
  Open: ${k}
981
- PID: ${x.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${x.pid} /F`:`kill ${x.pid}`}`}]})}catch(f){let m=f instanceof Error?f.message:String(f);return K("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${m}`}]})}});b2().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var Y$={};Le(Y$,{needsHookNormalization:()=>ca,normalizeHooksJson:()=>K$,normalizeHooksOnStartup:()=>S2,normalizePluginJson:()=>J$});import{existsSync as q$,readFileSync as V$,writeFileSync as W$}from"node:fs";import{resolve as G$}from"node:path";function ul(t){return String(t).replace(/\\/g,"/")}function ca(t){return!t||typeof t!="string"?!1:t.includes(aa)}function K$(t,e,r){if(!ca(t))return t;let n=ul(e),s=ul(r),o;try{o=JSON.parse(t)}catch{return t}let i=o?.hooks;if(!i||typeof i!="object")return t;let a=!1;for(let c of Object.keys(i)){let u=i[c];if(Array.isArray(u))for(let d of u){let l=d?.hooks;if(Array.isArray(l))for(let p of l){if(typeof p?.command!="string"||!p.command.includes(aa))continue;let f=p.command.replaceAll(aa,s);f=f.replace(/^\s*node\s+/,`"${n}" `),p.command=f,a=!0}}}return a?JSON.stringify(o,null,2):t}function J$(t,e,r){if(!ca(t))return t;let n=ul(e),s=ul(r),o;try{o=JSON.parse(t)}catch{return t}let i=o?.mcpServers;if(!i||typeof i!="object")return t;let a=!1;for(let c of Object.keys(i)){let u=i[c];if(!(!u||typeof u!="object")){if(Array.isArray(u.args)){let d=u.args,l=d.map(p=>typeof p=="string"&&p.includes(aa)?p.replaceAll(aa,s):p);l.some((p,f)=>p!==d[f])&&(u.args=l,a=!0)}u.command==="node"&&a&&(u.command=n)}}return a?JSON.stringify(o,null,2):t}function S2({pluginRoot:t,nodePath:e,platform:r}){if(r==="win32"&&!(!t||!e)){try{let n=G$(t,"hooks","hooks.json");if(q$(n)){let s=V$(n,"utf-8");if(ca(s)){let o=K$(s,e,t);o!==s&&W$(n,o,"utf-8")}}}catch{}try{let n=G$(t,".claude-plugin","plugin.json");if(q$(n)){let s=V$(n,"utf-8");if(ca(s)){let o=J$(s,e,t);o!==s&&W$(n,o,"utf-8")}}}catch{}}}var aa,X$=b(()=>{"use strict";aa="${CLAUDE_PLUGIN_ROOT}"});import{stdout as $T,stdin as TT}from"node:process";import*as Kr from"node:readline";var Hy=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,Zy=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,By=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var gl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,da=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,pa=/\t{1,1000}/y,yl=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),ma=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,hT=new RegExp("\\p{M}+","gu"),gT={limit:1/0,ellipsis:""},qy=(t,e={},r={})=>{let n=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?qy(s,gT,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,p=r.regularWidth??1,f=r.wideWidth??2,m=0,h=0,g=t.length,_=0,v=!1,y=g,x=Math.max(0,n-o),k=0,R=0,$=0,P=0;e:for(;;){if(R>k||h>=g&&h>m){let j=t.slice(k,R)||t.slice(m,h);_=0;for(let T of j.replaceAll(hT,"")){let C=T.codePointAt(0)||0;if(Zy(C)?P=l:By(C)?P=f:u!==p&&Hy(C)?P=u:P=p,$+P>x&&(y=Math.min(y,Math.max(k,m)+_)),$+P>n){v=!0;break e}_+=T.length,$+=P}k=R=0}if(h>=g)break;if(ma.lastIndex=h,ma.test(t)){if(_=ma.lastIndex-h,P=_*p,$+P>x&&(y=Math.min(y,h+Math.floor((x-$)/p))),$+P>n){v=!0;break}$+=P,k=m,R=h,h=m=ma.lastIndex;continue}if(gl.lastIndex=h,gl.test(t)){if($+i>x&&(y=Math.min(y,h)),$+i>n){v=!0;break}$+=i,k=m,R=h,h=m=gl.lastIndex;continue}if(da.lastIndex=h,da.test(t)){if(_=da.lastIndex-h,P=_*a,$+P>x&&(y=Math.min(y,h+Math.floor((x-$)/a))),$+P>n){v=!0;break}$+=P,k=m,R=h,h=m=da.lastIndex;continue}if(pa.lastIndex=h,pa.test(t)){if(_=pa.lastIndex-h,P=_*c,$+P>x&&(y=Math.min(y,h+Math.floor((x-$)/c))),$+P>n){v=!0;break}$+=P,k=m,R=h,h=m=pa.lastIndex;continue}if(yl.lastIndex=h,yl.test(t)){if($+d>x&&(y=Math.min(y,h)),$+d>n){v=!0;break}$+=d,k=m,R=h,h=m=yl.lastIndex;continue}h+=1}return{width:v?x:$,index:v?y:g,truncated:v,ellipsed:v&&n>=o}},Vy=qy;var yT={limit:1/0,ellipsis:"",ellipsisWidth:0},_T=(t,e={})=>Vy(t,yT,e).width,lt=_T;var fa="\x1B",Yy="\x9B",xT=39,xl="\x07",Xy="[",vT="]",Qy="m",vl=`${vT}8;;`,Wy=new RegExp(`(?:\\${Xy}(?<code>\\d+)m|\\${vl}(?<uri>.*)${xl})`,"y"),Gy=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Ky=t=>`${fa}${Xy}${t}${Qy}`,Jy=t=>`${fa}${vl}${t}${xl}`,_l=(t,e,r)=>{let n=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:lt(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,p=lt(l);a+p<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===fa||l===Yy)&&(s=!0,o=e.startsWith(vl,d+1)),s?o?l===xl&&(s=!1,o=!1):l===Qy&&(s=!1):(a+=p,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},bT=t=>{let e=t.split(" "),r=e.length;for(;r&&!lt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},ST=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",s,o,i=t.split(" "),a=[""],c=0;for(let l=0;l<i.length;l++){let p=i[l];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();m.length!==h.length&&(a[a.length-1]=h,c=lt(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=lt(p);if(r.hard&&f>e){let m=e-c,h=1+Math.floor((f-m-1)/e);Math.floor((f-1)/e)<h&&a.push(""),_l(a,p,e),c=lt(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){_l(a,p,e),c=lt(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){_l(a,p,e),c=lt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}r.trim!==!1&&(a=a.map(l=>bT(l)));let u=a.join(`
982
- `),d=!1;for(let l=0;l<u.length;l++){let p=u[l];if(n+=p,!d)d=p>="\uD800"&&p<="\uDBFF";else continue;if(p===fa||p===Yy){Wy.lastIndex=l+1;let m=Wy.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);s=h===xT?void 0:h}else m?.uri!==void 0&&(o=m.uri.length===0?void 0:m.uri)}if(u[l+1]===`
983
- `){o&&(n+=Jy(""));let f=s?Gy(s):void 0;s&&f&&(n+=Ky(f))}else p===`
984
- `&&(s&&Gy(s)&&(n+=Ky(s)),o&&(n+=Jy(o)))}return n},kT=/\r?\n/;function xs(t,e,r){return String(t).normalize().split(kT).map(n=>ST(n,e,r)).join(`
985
- `)}var Ro=Po(Sl(),1);import{ReadStream as t_}from"node:tty";var PT=["up","down","left","right","space","enter","cancel"],RT=["January","February","March","April","May","June","July","August","September","October","November","December"],xr={actions:new Set(PT),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...RT],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function r_(t,e){if(typeof t=="string")return xr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&r_(r,e))return!0;return!1}var CT=globalThis.process.platform.startsWith("win");function n_({input:t=TT,output:e=$T,overwrite:r=!0,hideCursor:n=!0}={}){let s=Kr.createInterface({input:t,output:e,prompt:"",tabSize:1});Kr.emitKeypressEvents(t,s),t instanceof t_&&t.isTTY&&t.setRawMode(!0);let o=(i,{name:a,sequence:c})=>{let u=String(i);if(r_([u,a,c],"cancel")){n&&e.write(Ro.cursor.show),process.exit(0);return}if(!r)return;Kr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{Kr.clearLine(e,1,()=>{t.once("keypress",o)})})};return n&&e.write(Ro.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),n&&e.write(Ro.cursor.show),t instanceof t_&&t.isTTY&&!CT&&t.setRawMode(!1),s.terminal=!1,s.close()}}var kl=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Oe,stripVTControlCharacters as xU}from"node:util";import zt from"node:process";var Co=Po(Sl(),1);function IT(){return zt.platform!=="win32"?zt.env.TERM!=="linux":!!zt.env.CI||!!zt.env.WT_SESSION||!!zt.env.TERMINUS_SUBLIME||zt.env.ConEmuTask==="{cmd::Cmder}"||zt.env.TERM_PROGRAM==="Terminus-Sublime"||zt.env.TERM_PROGRAM==="vscode"||zt.env.TERM==="xterm-256color"||zt.env.TERM==="alacritty"||zt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var wl=IT(),AT=()=>process.env.CI==="true";var ye=(t,e)=>wl?t:e,kU=ye("\u25C6","*"),NT=ye("\u25A0","x"),DT=ye("\u25B2","x"),El=ye("\u25C7","o"),MT=ye("\u250C","T"),Jr=ye("\u2502","|"),jT=ye("\u2514","\u2014"),wU=ye("\u2510","T"),EU=ye("\u2518","\u2014"),$U=ye("\u25CF",">"),TU=ye("\u25CB"," "),PU=ye("\u25FB","[\u2022]"),RU=ye("\u25FC","[+]"),CU=ye("\u25FB","[ ]"),OU=ye("\u25AA","\u2022"),s_=ye("\u2500","-"),zT=ye("\u256E","+"),LT=ye("\u251C","+"),FT=ye("\u256F","+"),UT=ye("\u2570","+"),IU=ye("\u256D","+"),HT=ye("\u25CF","\u2022"),ZT=ye("\u25C6","*"),BT=ye("\u25B2","!"),qT=ye("\u25A0","x");var A={message:(t=[],{symbol:e=Oe("gray",Jr),secondarySymbol:r=Oe("gray",Jr),output:n=process.stdout,spacing:s=1,withGuide:o}={})=>{let i=[],a=o??xr.withGuide,c=a?r:"",u=a?`${e} `:"",d=a?`${r} `:"";for(let p=0;p<s;p++)i.push(c);let l=Array.isArray(t)?t:t.split(`
981
+ PID: ${x.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${x.pid} /F`:`kill ${x.pid}`}`}]})}catch(f){let m=f instanceof Error?f.message:String(f);return K("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${m}`}]})}});T2().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var X$={};Le(X$,{needsHookNormalization:()=>ua,normalizeHooksJson:()=>J$,normalizeHooksOnStartup:()=>P2,normalizePluginJson:()=>Y$});import{existsSync as V$,readFileSync as W$,writeFileSync as G$}from"node:fs";import{resolve as K$}from"node:path";function ll(t){return String(t).replace(/\\/g,"/")}function ua(t){return!t||typeof t!="string"?!1:t.includes(ca)}function J$(t,e,r){if(!ua(t))return t;let n=ll(e),s=ll(r),o;try{o=JSON.parse(t)}catch{return t}let i=o?.hooks;if(!i||typeof i!="object")return t;let a=!1;for(let c of Object.keys(i)){let u=i[c];if(Array.isArray(u))for(let d of u){let l=d?.hooks;if(Array.isArray(l))for(let p of l){if(typeof p?.command!="string"||!p.command.includes(ca))continue;let f=p.command.replaceAll(ca,s);f=f.replace(/^\s*node\s+/,`"${n}" `),p.command=f,a=!0}}}return a?JSON.stringify(o,null,2):t}function Y$(t,e,r){if(!ua(t))return t;let n=ll(e),s=ll(r),o;try{o=JSON.parse(t)}catch{return t}let i=o?.mcpServers;if(!i||typeof i!="object")return t;let a=!1;for(let c of Object.keys(i)){let u=i[c];if(!(!u||typeof u!="object")){if(Array.isArray(u.args)){let d=u.args,l=d.map(p=>typeof p=="string"&&p.includes(ca)?p.replaceAll(ca,s):p);l.some((p,f)=>p!==d[f])&&(u.args=l,a=!0)}u.command==="node"&&a&&(u.command=n)}}return a?JSON.stringify(o,null,2):t}function P2({pluginRoot:t,nodePath:e,platform:r}){if(r==="win32"&&!(!t||!e)){try{let n=K$(t,"hooks","hooks.json");if(V$(n)){let s=W$(n,"utf-8");if(ua(s)){let o=J$(s,e,t);o!==s&&G$(n,o,"utf-8")}}}catch{}try{let n=K$(t,".claude-plugin","plugin.json");if(V$(n)){let s=W$(n,"utf-8");if(ua(s)){let o=Y$(s,e,t);o!==s&&G$(n,o,"utf-8")}}}catch{}}}var ca,Q$=b(()=>{"use strict";ca="${CLAUDE_PLUGIN_ROOT}"});import{stdout as TT,stdin as PT}from"node:process";import*as Kr from"node:readline";var By=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,qy=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Vy=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var yl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,pa=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ma=/\t{1,1000}/y,_l=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),fa=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,gT=new RegExp("\\p{M}+","gu"),yT={limit:1/0,ellipsis:""},Wy=(t,e={},r={})=>{let n=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?Wy(s,yT,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,p=r.regularWidth??1,f=r.wideWidth??2,m=0,h=0,g=t.length,_=0,v=!1,y=g,x=Math.max(0,n-o),k=0,R=0,$=0,P=0;e:for(;;){if(R>k||h>=g&&h>m){let j=t.slice(k,R)||t.slice(m,h);_=0;for(let T of j.replaceAll(gT,"")){let C=T.codePointAt(0)||0;if(qy(C)?P=l:Vy(C)?P=f:u!==p&&By(C)?P=u:P=p,$+P>x&&(y=Math.min(y,Math.max(k,m)+_)),$+P>n){v=!0;break e}_+=T.length,$+=P}k=R=0}if(h>=g)break;if(fa.lastIndex=h,fa.test(t)){if(_=fa.lastIndex-h,P=_*p,$+P>x&&(y=Math.min(y,h+Math.floor((x-$)/p))),$+P>n){v=!0;break}$+=P,k=m,R=h,h=m=fa.lastIndex;continue}if(yl.lastIndex=h,yl.test(t)){if($+i>x&&(y=Math.min(y,h)),$+i>n){v=!0;break}$+=i,k=m,R=h,h=m=yl.lastIndex;continue}if(pa.lastIndex=h,pa.test(t)){if(_=pa.lastIndex-h,P=_*a,$+P>x&&(y=Math.min(y,h+Math.floor((x-$)/a))),$+P>n){v=!0;break}$+=P,k=m,R=h,h=m=pa.lastIndex;continue}if(ma.lastIndex=h,ma.test(t)){if(_=ma.lastIndex-h,P=_*c,$+P>x&&(y=Math.min(y,h+Math.floor((x-$)/c))),$+P>n){v=!0;break}$+=P,k=m,R=h,h=m=ma.lastIndex;continue}if(_l.lastIndex=h,_l.test(t)){if($+d>x&&(y=Math.min(y,h)),$+d>n){v=!0;break}$+=d,k=m,R=h,h=m=_l.lastIndex;continue}h+=1}return{width:v?x:$,index:v?y:g,truncated:v,ellipsed:v&&n>=o}},Gy=Wy;var _T={limit:1/0,ellipsis:"",ellipsisWidth:0},xT=(t,e={})=>Gy(t,_T,e).width,lt=xT;var ha="\x1B",Qy="\x9B",vT=39,vl="\x07",e_="[",bT="]",t_="m",bl=`${bT}8;;`,Ky=new RegExp(`(?:\\${e_}(?<code>\\d+)m|\\${bl}(?<uri>.*)${vl})`,"y"),Jy=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Yy=t=>`${ha}${e_}${t}${t_}`,Xy=t=>`${ha}${bl}${t}${vl}`,xl=(t,e,r)=>{let n=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:lt(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,p=lt(l);a+p<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===ha||l===Qy)&&(s=!0,o=e.startsWith(bl,d+1)),s?o?l===vl&&(s=!1,o=!1):l===t_&&(s=!1):(a+=p,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},ST=t=>{let e=t.split(" "),r=e.length;for(;r&&!lt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},kT=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",s,o,i=t.split(" "),a=[""],c=0;for(let l=0;l<i.length;l++){let p=i[l];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();m.length!==h.length&&(a[a.length-1]=h,c=lt(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=lt(p);if(r.hard&&f>e){let m=e-c,h=1+Math.floor((f-m-1)/e);Math.floor((f-1)/e)<h&&a.push(""),xl(a,p,e),c=lt(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){xl(a,p,e),c=lt(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){xl(a,p,e),c=lt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}r.trim!==!1&&(a=a.map(l=>ST(l)));let u=a.join(`
982
+ `),d=!1;for(let l=0;l<u.length;l++){let p=u[l];if(n+=p,!d)d=p>="\uD800"&&p<="\uDBFF";else continue;if(p===ha||p===Qy){Ky.lastIndex=l+1;let m=Ky.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);s=h===vT?void 0:h}else m?.uri!==void 0&&(o=m.uri.length===0?void 0:m.uri)}if(u[l+1]===`
983
+ `){o&&(n+=Xy(""));let f=s?Jy(s):void 0;s&&f&&(n+=Yy(f))}else p===`
984
+ `&&(s&&Jy(s)&&(n+=Yy(s)),o&&(n+=Xy(o)))}return n},wT=/\r?\n/;function vs(t,e,r){return String(t).normalize().split(wT).map(n=>kT(n,e,r)).join(`
985
+ `)}var Ro=Po(kl(),1);import{ReadStream as n_}from"node:tty";var RT=["up","down","left","right","space","enter","cancel"],CT=["January","February","March","April","May","June","July","August","September","October","November","December"],xr={actions:new Set(RT),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...CT],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function s_(t,e){if(typeof t=="string")return xr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&s_(r,e))return!0;return!1}var OT=globalThis.process.platform.startsWith("win");function o_({input:t=PT,output:e=TT,overwrite:r=!0,hideCursor:n=!0}={}){let s=Kr.createInterface({input:t,output:e,prompt:"",tabSize:1});Kr.emitKeypressEvents(t,s),t instanceof n_&&t.isTTY&&t.setRawMode(!0);let o=(i,{name:a,sequence:c})=>{let u=String(i);if(s_([u,a,c],"cancel")){n&&e.write(Ro.cursor.show),process.exit(0);return}if(!r)return;Kr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{Kr.clearLine(e,1,()=>{t.once("keypress",o)})})};return n&&e.write(Ro.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),n&&e.write(Ro.cursor.show),t instanceof n_&&t.isTTY&&!OT&&t.setRawMode(!1),s.terminal=!1,s.close()}}var wl=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Oe,stripVTControlCharacters as EU}from"node:util";import zt from"node:process";var Co=Po(kl(),1);function AT(){return zt.platform!=="win32"?zt.env.TERM!=="linux":!!zt.env.CI||!!zt.env.WT_SESSION||!!zt.env.TERMINUS_SUBLIME||zt.env.ConEmuTask==="{cmd::Cmder}"||zt.env.TERM_PROGRAM==="Terminus-Sublime"||zt.env.TERM_PROGRAM==="vscode"||zt.env.TERM==="xterm-256color"||zt.env.TERM==="alacritty"||zt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var El=AT(),NT=()=>process.env.CI==="true";var ye=(t,e)=>El?t:e,RU=ye("\u25C6","*"),DT=ye("\u25A0","x"),MT=ye("\u25B2","x"),$l=ye("\u25C7","o"),jT=ye("\u250C","T"),Jr=ye("\u2502","|"),zT=ye("\u2514","\u2014"),CU=ye("\u2510","T"),OU=ye("\u2518","\u2014"),IU=ye("\u25CF",">"),AU=ye("\u25CB"," "),NU=ye("\u25FB","[\u2022]"),DU=ye("\u25FC","[+]"),MU=ye("\u25FB","[ ]"),jU=ye("\u25AA","\u2022"),i_=ye("\u2500","-"),LT=ye("\u256E","+"),FT=ye("\u251C","+"),UT=ye("\u256F","+"),HT=ye("\u2570","+"),zU=ye("\u256D","+"),ZT=ye("\u25CF","\u2022"),BT=ye("\u25C6","*"),qT=ye("\u25B2","!"),VT=ye("\u25A0","x");var A={message:(t=[],{symbol:e=Oe("gray",Jr),secondarySymbol:r=Oe("gray",Jr),output:n=process.stdout,spacing:s=1,withGuide:o}={})=>{let i=[],a=o??xr.withGuide,c=a?r:"",u=a?`${e} `:"",d=a?`${r} `:"";for(let p=0;p<s;p++)i.push(c);let l=Array.isArray(t)?t:t.split(`
986
986
  `);if(l.length>0){let[p,...f]=l;p.length>0?i.push(`${u}${p}`):i.push(a?e:"");for(let m of f)m.length>0?i.push(`${d}${m}`):i.push(a?r:"")}n.write(`${i.join(`
987
987
  `)}
988
- `)},info:(t,e)=>{A.message(t,{...e,symbol:Oe("blue",HT)})},success:(t,e)=>{A.message(t,{...e,symbol:Oe("green",ZT)})},step:(t,e)=>{A.message(t,{...e,symbol:Oe("green",El)})},warn:(t,e)=>{A.message(t,{...e,symbol:Oe("yellow",BT)})},warning:(t,e)=>{A.warn(t,e)},error:(t,e)=>{A.message(t,{...e,symbol:Oe("red",qT)})}};var $l=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Oe("gray",MT)} `:"";r.write(`${n}${t}
989
- `)},ha=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Oe("gray",Jr)}
990
- ${Oe("gray",jT)} `:"";r.write(`${n}${t}
988
+ `)},info:(t,e)=>{A.message(t,{...e,symbol:Oe("blue",ZT)})},success:(t,e)=>{A.message(t,{...e,symbol:Oe("green",BT)})},step:(t,e)=>{A.message(t,{...e,symbol:Oe("green",$l)})},warn:(t,e)=>{A.message(t,{...e,symbol:Oe("yellow",qT)})},warning:(t,e)=>{A.warn(t,e)},error:(t,e)=>{A.message(t,{...e,symbol:Oe("red",VT)})}};var Tl=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Oe("gray",jT)} `:"";r.write(`${n}${t}
989
+ `)},ga=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Oe("gray",Jr)}
990
+ ${Oe("gray",zT)} `:"";r.write(`${n}${t}
991
991
 
992
- `)};var VT=t=>Oe("dim",t),WT=(t,e,r)=>{let n={hard:!0,trim:!1},s=xs(t,e,n).split(`
993
- `),o=s.reduce((c,u)=>Math.max(lt(u),c),0),i=s.map(r).reduce((c,u)=>Math.max(lt(u),c),0),a=e-(i-o);return xs(t,a,n)},Tl=(t="",e="",r)=>{let n=r?.output??zt.stdout,s=r?.withGuide??xr.withGuide,o=r?.format??VT,i=["",...WT(t,kl(n)-6,o).split(`
992
+ `)};var WT=t=>Oe("dim",t),GT=(t,e,r)=>{let n={hard:!0,trim:!1},s=vs(t,e,n).split(`
993
+ `),o=s.reduce((c,u)=>Math.max(lt(u),c),0),i=s.map(r).reduce((c,u)=>Math.max(lt(u),c),0),a=e-(i-o);return vs(t,a,n)},Pl=(t="",e="",r)=>{let n=r?.output??zt.stdout,s=r?.withGuide??xr.withGuide,o=r?.format??WT,i=["",...GT(t,wl(n)-6,o).split(`
994
994
  `).map(o),""],a=lt(e),c=Math.max(i.reduce((p,f)=>{let m=lt(f);return m>p?m:p},0),a)+2,u=i.map(p=>`${Oe("gray",Jr)} ${p}${" ".repeat(c-lt(p))}${Oe("gray",Jr)}`).join(`
995
995
  `),d=s?`${Oe("gray",Jr)}
996
- `:"",l=s?LT:UT;n.write(`${d}${Oe("green",El)} ${Oe("reset",e)} ${Oe("gray",s_.repeat(Math.max(c-a-1,1))+zT)}
996
+ `:"",l=s?FT:HT;n.write(`${d}${Oe("green",$l)} ${Oe("reset",e)} ${Oe("gray",i_.repeat(Math.max(c-a-1,1))+LT)}
997
997
  ${u}
998
- ${Oe("gray",l+s_.repeat(c+2)+FT)}
999
- `)};var GT=t=>Oe("magenta",t),Pl=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:o=wl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=wl?80:120,signal:a,...c}={})=>{let u=AT(),d,l,p=!1,f=!1,m="",h,g=performance.now(),_=kl(r),v=c?.styleFrame??GT,y=ae=>{let yt=ae>1?s??xr.messages.error:n??xr.messages.cancel;f=ae===1,p&&(X(yt,ae),f&&typeof e=="function"&&e())},x=()=>y(2),k=()=>y(1),R=()=>{process.on("uncaughtExceptionMonitor",x),process.on("unhandledRejection",x),process.on("SIGINT",k),process.on("SIGTERM",k),process.on("exit",y),a&&a.addEventListener("abort",k)},$=()=>{process.removeListener("uncaughtExceptionMonitor",x),process.removeListener("unhandledRejection",x),process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),process.removeListener("exit",y),a&&a.removeEventListener("abort",k)},P=()=>{if(h===void 0)return;u&&r.write(`
1000
- `);let ae=xs(h,_,{hard:!0,trim:!1}).split(`
1001
- `);ae.length>1&&r.write(Co.cursor.up(ae.length-1)),r.write(Co.cursor.to(0)),r.write(Co.erase.down())},j=ae=>ae.replace(/\.+$/,""),T=ae=>{let yt=(performance.now()-ae)/1e3,jt=Math.floor(yt/60),_t=Math.floor(yt%60);return jt>0?`[${jt}m ${_t}s]`:`[${_t}s]`},C=c.withGuide??xr.withGuide,L=(ae="")=>{p=!0,d=n_({output:r}),m=j(ae),g=performance.now(),C&&r.write(`${Oe("gray",Jr)}
1002
- `);let yt=0,jt=0;R(),l=setInterval(()=>{if(u&&m===h)return;P(),h=m;let _t=v(o[yt]),_s;if(u)_s=`${_t} ${m}...`;else if(t==="timer")_s=`${_t} ${m} ${T(g)}`;else{let fl=".".repeat(Math.floor(jt)).slice(0,3);_s=`${_t} ${m}${fl}`}let ml=xs(_s,_,{hard:!0,trim:!1});r.write(ml),yt=yt+1<o.length?yt+1:0,jt=jt<4?jt+.125:0},i)},X=(ae="",yt=0,jt=!1)=>{if(!p)return;p=!1,clearInterval(l),P();let _t=yt===0?Oe("green",El):yt===1?Oe("red",NT):Oe("red",DT);m=ae??m,jt||(t==="timer"?r.write(`${_t} ${m} ${T(g)}
998
+ ${Oe("gray",l+i_.repeat(c+2)+UT)}
999
+ `)};var KT=t=>Oe("magenta",t),Rl=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:o=El?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=El?80:120,signal:a,...c}={})=>{let u=NT(),d,l,p=!1,f=!1,m="",h,g=performance.now(),_=wl(r),v=c?.styleFrame??KT,y=ae=>{let yt=ae>1?s??xr.messages.error:n??xr.messages.cancel;f=ae===1,p&&(X(yt,ae),f&&typeof e=="function"&&e())},x=()=>y(2),k=()=>y(1),R=()=>{process.on("uncaughtExceptionMonitor",x),process.on("unhandledRejection",x),process.on("SIGINT",k),process.on("SIGTERM",k),process.on("exit",y),a&&a.addEventListener("abort",k)},$=()=>{process.removeListener("uncaughtExceptionMonitor",x),process.removeListener("unhandledRejection",x),process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),process.removeListener("exit",y),a&&a.removeEventListener("abort",k)},P=()=>{if(h===void 0)return;u&&r.write(`
1000
+ `);let ae=vs(h,_,{hard:!0,trim:!1}).split(`
1001
+ `);ae.length>1&&r.write(Co.cursor.up(ae.length-1)),r.write(Co.cursor.to(0)),r.write(Co.erase.down())},j=ae=>ae.replace(/\.+$/,""),T=ae=>{let yt=(performance.now()-ae)/1e3,jt=Math.floor(yt/60),_t=Math.floor(yt%60);return jt>0?`[${jt}m ${_t}s]`:`[${_t}s]`},C=c.withGuide??xr.withGuide,L=(ae="")=>{p=!0,d=o_({output:r}),m=j(ae),g=performance.now(),C&&r.write(`${Oe("gray",Jr)}
1002
+ `);let yt=0,jt=0;R(),l=setInterval(()=>{if(u&&m===h)return;P(),h=m;let _t=v(o[yt]),xs;if(u)xs=`${_t} ${m}...`;else if(t==="timer")xs=`${_t} ${m} ${T(g)}`;else{let hl=".".repeat(Math.floor(jt)).slice(0,3);xs=`${_t} ${m}${hl}`}let fl=vs(xs,_,{hard:!0,trim:!1});r.write(fl),yt=yt+1<o.length?yt+1:0,jt=jt<4?jt+.125:0},i)},X=(ae="",yt=0,jt=!1)=>{if(!p)return;p=!1,clearInterval(l),P();let _t=yt===0?Oe("green",$l):yt===1?Oe("red",DT):Oe("red",MT);m=ae??m,jt||(t==="timer"?r.write(`${_t} ${m} ${T(g)}
1003
1003
  `):r.write(`${_t} ${m}
1004
- `)),$(),d()};return{start:L,stop:(ae="")=>X(ae,0),message:(ae="")=>{m=j(ae??m)},cancel:(ae="")=>X(ae,1),error:(ae="")=>X(ae,2),clear:()=>X("",0,!0),get isCancelled(){return f}}},AU={light:ye("\u2500","-"),heavy:ye("\u2501","="),block:ye("\u2588","#")};var NU=`${Oe("gray",Jr)} `;var E=Po(a_(),1);ba();Ol();Yr();import{execFileSync as $o,execSync as k2,execFile as w2}from"node:child_process";import{readFileSync as Wr,writeFileSync as E2,cpSync as Q$,accessSync as tT,existsSync as Fe,rmSync as To,closeSync as $2,openSync as T2,chmodSync as P2,constants as rT}from"node:fs";import{request as R2}from"node:https";import{resolve as ue,dirname as zy,join as gt}from"node:path";import{tmpdir as C2,devNull as O2,homedir as eT}from"node:os";import{fileURLToPath as I2,pathToFileURL as dl}from"node:url";import{existsSync as p_,readFileSync as m_,writeFileSync as f_}from"node:fs";import{resolve as Ss,sep as h_}from"node:path";var g_=/[/\\]context-mode-upgrade-\d+[/\\]/,Nl="${CLAUDE_PLUGIN_ROOT}/start.mjs";function Dl({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=Ss(t),s=Ss(e)+h_;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=Ss(t,".claude-plugin","plugin.json");if(!p_(o))return{healed:[],skipped:"no-plugin-json"};let i;try{i=m_(o,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],p=d.args,f=p.map(h=>typeof h!="string"?h:g_.test(h)&&/[/\\]start\.mjs$/.test(h)?Nl:h);if(f.some((h,g)=>h!==p[g])){d.args=f,l.push("plugin-json-args");try{f_(o,JSON.stringify(a,null,2)+`
1005
- `,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function Ml({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=Ss(t),s=Ss(e)+h_;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=Ss(t,".mcp.json");if(!p_(o))return{healed:[],skipped:"no-mcp-json"};let i;try{i=m_(o,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],p=d.args,f=p.map(h=>typeof h!="string"?h:h==="./start.mjs"||h==="start.mjs"||g_.test(h)&&/[/\\]start\.mjs$/.test(h)?Nl:h);if(f.some((h,g)=>h!==p[g])){d.args=f,l.push("mcp-json-args");try{f_(o,JSON.stringify(a,null,2)+`
1006
- `,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}Os();function A2(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}var N2={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"},"gemini-cli":{beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function D2(t,e){try{$2(2),T2(O2,"w")}catch{process.stderr.write=(()=>!0)}let r=N2[t]?.[e];r||process.exit(1);let n=ys();await import(dl(gt(n,r)).href)}var tr=process.argv.slice(2);if(tr[0]==="doctor")U2().then(t=>process.exit(t));else if(tr[0]==="upgrade"){let t=tr.indexOf("--platform"),e=t>=0&&tr[t+1]?tr[t+1]:void 0;Z2(e?{platform:e}:void 0).catch(r=>{let n=r instanceof Error?r.message:String(r);A.error(E.default.red(n)),process.exit(1)})}else tr[0]==="hook"?D2(tr[1],tr[2]):tr[0]==="insight"?H2(tr[1]?Number(tr[1]):4747):tr[0]==="statusline"?B2():Promise.resolve().then(()=>(B$(),Z$));function oG(t){return t.replace(/\\/g,"/")}var pl=process.platform==="win32";function ll(t,e={}){$o(pl?"npm.cmd":"npm",t,{...e,...pl?{shell:!0}:{}})}function M2(t,e={}){let r={...e,...pl?{shell:!0}:{}};k2(pl?t.replace(/^npm /,"npm.cmd "):t,r)}function j2(t,e=process.platform,r=w2){let n={stdio:"ignore"},s=()=>console.error(`
1007
- Could not auto-open browser. Open manually: ${t}`),o=A2(t,e),i=!1;for(let{cmd:a,args:c}of o)try{r(a,c,n),i=!0;break}catch{}i||s()}function z2(){let t=I2(import.meta.url),e=zy(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?ue(e,".."):e}function L2(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?ue(r,t,...e):ue(eT(),"AppData","Local",t,...e)}return ue(eT(),".cache",t,...e)}function ys(){let t=sr().platform;return t==="opencode"||t==="kilo"?L2(t):z2()}function nT(){try{return JSON.parse(Wr(ue(ys(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function F2(){return new Promise(t=>{let e=R2("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",s=>{n+=s}),r.on("end",()=>{try{let s=JSON.parse(n);t(s.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}async function U2(){process.stdout.isTTY&&console.clear();let t=sr(),e=await jo(t.platform);$l(E.default.bgMagenta(E.default.white(" context-mode doctor "))),A.info(`Platform: ${E.default.cyan(e.name)}`+E.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0,n=Pl();n.start("Running diagnostics");let s,o;try{s=vs(),o=va(s)}catch{return n.stop("Diagnostics partial"),A.warn(E.default.yellow("Could not detect runtimes")+E.default.dim(" \u2014 module may be missing, restart session after upgrade")),ha(E.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),Tl(xa(s),"Runtimes"),bs()?A.success(E.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):A.warn(E.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(o.length/i*100).toFixed(0);o.length<2?(r++,A.error(E.default.red(`Language coverage: ${o.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+E.default.dim(` \u2014 ${o.join(", ")||"none"}`))):A.info(`Language coverage: ${o.length}/${i} (${a}%)`+E.default.dim(` \u2014 ${o.join(", ")}`)),A.step("Testing server initialization...");try{let{PolyglotExecutor:h}=await Promise.resolve().then(()=>(Xg(),gE)),_=await new h({runtimes:s}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(_.exitCode===0&&_.stdout.trim()==="ok")A.success(E.default.green("Server test: PASS"));else{r++;let v=_.stderr?.trim()?` (${_.stderr.trim().slice(0,200)})`:"";A.error(E.default.red("Server test: FAIL")+` \u2014 exit ${_.exitCode}${v}`)}}catch(h){let g=h instanceof Error?h.message:String(h);g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?A.warn(E.default.yellow("Server test: SKIP")+E.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,A.error(E.default.red("Server test: FAIL")+` \u2014 ${g}`))}A.step(`Checking ${e.name} hooks configuration...`);let c=ys(),u=e.validateHooks(c);for(let h of u)h.status==="pass"?A.success(E.default.green(`${h.check}: PASS`)+` \u2014 ${h.message}`):h.status==="warn"?A.warn(E.default.yellow(`${h.check}: WARN`)+` \u2014 ${h.message}`+(h.fix?E.default.dim(`
1004
+ `)),$(),d()};return{start:L,stop:(ae="")=>X(ae,0),message:(ae="")=>{m=j(ae??m)},cancel:(ae="")=>X(ae,1),error:(ae="")=>X(ae,2),clear:()=>X("",0,!0),get isCancelled(){return f}}},LU={light:ye("\u2500","-"),heavy:ye("\u2501","="),block:ye("\u2588","#")};var FU=`${Oe("gray",Jr)} `;var E=Po(u_(),1);Sa();Il();Yr();import{execFileSync as $o,execSync as R2,execFile as C2}from"node:child_process";import{readFileSync as Wr,writeFileSync as O2,cpSync as eT,accessSync as rT,existsSync as Fe,rmSync as To,closeSync as I2,openSync as A2,chmodSync as N2,constants as nT}from"node:fs";import{request as D2}from"node:https";import{resolve as ue,dirname as Fy,join as gt}from"node:path";import{tmpdir as M2,devNull as j2,homedir as tT}from"node:os";import{fileURLToPath as z2,pathToFileURL as pl}from"node:url";import{existsSync as f_,readFileSync as h_,writeFileSync as g_}from"node:fs";import{resolve as ks,sep as y_}from"node:path";var __=/[/\\]context-mode-upgrade-\d+[/\\]/,Dl="${CLAUDE_PLUGIN_ROOT}/start.mjs";function Ml({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=ks(t),s=ks(e)+y_;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=ks(t,".claude-plugin","plugin.json");if(!f_(o))return{healed:[],skipped:"no-plugin-json"};let i;try{i=h_(o,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],p=d.args,f=p.map(h=>typeof h!="string"?h:__.test(h)&&/[/\\]start\.mjs$/.test(h)?Dl:h);if(f.some((h,g)=>h!==p[g])){d.args=f,l.push("plugin-json-args");try{g_(o,JSON.stringify(a,null,2)+`
1005
+ `,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function jl({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=ks(t),s=ks(e)+y_;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=ks(t,".mcp.json");if(!f_(o))return{healed:[],skipped:"no-mcp-json"};let i;try{i=h_(o,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],p=d.args,f=p.map(h=>typeof h!="string"?h:h==="./start.mjs"||h==="start.mjs"||__.test(h)&&/[/\\]start\.mjs$/.test(h)?Dl:h);if(f.some((h,g)=>h!==p[g])){d.args=f,l.push("mcp-json-args");try{g_(o,JSON.stringify(a,null,2)+`
1006
+ `,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}An();function L2(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}var F2={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"},"gemini-cli":{beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function U2(t,e){try{I2(2),A2(j2,"w")}catch{process.stderr.write=(()=>!0)}let r=F2[t]?.[e];r||process.exit(1);let n=_s();await import(pl(gt(n,r)).href)}var tr=process.argv.slice(2);if(tr[0]==="doctor")W2().then(t=>process.exit(t));else if(tr[0]==="upgrade"){let t=tr.indexOf("--platform"),e=t>=0&&tr[t+1]?tr[t+1]:void 0;K2(e?{platform:e}:void 0).catch(r=>{let n=r instanceof Error?r.message:String(r);A.error(E.default.red(n)),process.exit(1)})}else tr[0]==="hook"?U2(tr[1],tr[2]):tr[0]==="insight"?G2(tr[1]?Number(tr[1]):4747):tr[0]==="statusline"?J2():Promise.resolve().then(()=>(q$(),B$));function pG(t){return t.replace(/\\/g,"/")}var ml=process.platform==="win32";function dl(t,e={}){$o(ml?"npm.cmd":"npm",t,{...e,...ml?{shell:!0}:{}})}function H2(t,e={}){let r={...e,...ml?{shell:!0}:{}};R2(ml?t.replace(/^npm /,"npm.cmd "):t,r)}function Z2(t,e=process.platform,r=C2){let n={stdio:"ignore"},s=()=>console.error(`
1007
+ Could not auto-open browser. Open manually: ${t}`),o=L2(t,e),i=!1;for(let{cmd:a,args:c}of o)try{r(a,c,n),i=!0;break}catch{}i||s()}function B2(){let t=z2(import.meta.url),e=Fy(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?ue(e,".."):e}function q2(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?ue(r,t,...e):ue(tT(),"AppData","Local",t,...e)}return ue(tT(),".cache",t,...e)}function _s(){let t=sr().platform;return t==="opencode"||t==="kilo"?q2(t):B2()}function sT(){try{return JSON.parse(Wr(ue(_s(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function V2(){return new Promise(t=>{let e=D2("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",s=>{n+=s}),r.on("end",()=>{try{let s=JSON.parse(n);t(s.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}async function W2(){process.stdout.isTTY&&console.clear();let t=sr(),e=await zo(t.platform);Tl(E.default.bgMagenta(E.default.white(" context-mode doctor "))),A.info(`Platform: ${E.default.cyan(e.name)}`+E.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0,n=Rl();n.start("Running diagnostics");let s,o;try{s=bs(),o=ba(s)}catch{return n.stop("Diagnostics partial"),A.warn(E.default.yellow("Could not detect runtimes")+E.default.dim(" \u2014 module may be missing, restart session after upgrade")),ga(E.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),Pl(va(s),"Runtimes"),Ss()?A.success(E.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):A.warn(E.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(o.length/i*100).toFixed(0);o.length<2?(r++,A.error(E.default.red(`Language coverage: ${o.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+E.default.dim(` \u2014 ${o.join(", ")||"none"}`))):A.info(`Language coverage: ${o.length}/${i} (${a}%)`+E.default.dim(` \u2014 ${o.join(", ")}`)),A.step("Testing server initialization...");try{let{PolyglotExecutor:h}=await Promise.resolve().then(()=>(ey(),yE)),_=await new h({runtimes:s}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(_.exitCode===0&&_.stdout.trim()==="ok")A.success(E.default.green("Server test: PASS"));else{r++;let v=_.stderr?.trim()?` (${_.stderr.trim().slice(0,200)})`:"";A.error(E.default.red("Server test: FAIL")+` \u2014 exit ${_.exitCode}${v}`)}}catch(h){let g=h instanceof Error?h.message:String(h);g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?A.warn(E.default.yellow("Server test: SKIP")+E.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,A.error(E.default.red("Server test: FAIL")+` \u2014 ${g}`))}A.step(`Checking ${e.name} hooks configuration...`);let c=_s(),u=e.validateHooks(c);for(let h of u)h.status==="pass"?A.success(E.default.green(`${h.check}: PASS`)+` \u2014 ${h.message}`):h.status==="warn"?A.warn(E.default.yellow(`${h.check}: WARN`)+` \u2014 ${h.message}`+(h.fix?E.default.dim(`
1008
1008
  Run: ${h.fix}`):"")):A.error(E.default.red(`${h.check}: FAIL`)+` \u2014 ${h.message}`+(h.fix?E.default.dim(`
1009
- Run: ${h.fix}`):""));A.step("Checking hook scripts...");let d=Sa(e,c);if(d.length===0)A.success(E.default.green("Hook scripts: PASS")+E.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let h of d){let g=ue(c,h);try{tT(g,rT.R_OK),A.success(E.default.green("Hook script exists: PASS")+E.default.dim(` \u2014 ${g}`))}catch{A.error(E.default.red("Hook script exists: FAIL")+E.default.dim(` \u2014 not found at ${g}`))}}A.step(`Checking ${e.name} plugin registration...`);let l=e.checkPluginRegistration();l.status==="pass"?A.success(E.default.green("Plugin enabled: PASS")+E.default.dim(` \u2014 ${l.message}`)):A.warn(E.default.yellow("Plugin enabled: WARN")+` \u2014 ${l.message}`),A.step("Checking FTS5 / SQLite...");try{let h=(await Promise.resolve().then(()=>(ms(),bE))).loadDatabase(),g=new h(":memory:");g.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),g.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let _=g.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();g.close(),_&&_.content==="hello world"?A.success(E.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,A.error(E.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(h){let g=h instanceof Error?h.message:String(h),_=ys(),v=ue(_,"node_modules","better-sqlite3");!Fe(v)?(r++,A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+E.default.dim(" \u2014 package-missing")+E.default.dim(`
1009
+ Run: ${h.fix}`):""));A.step("Checking hook scripts...");let d=ka(e,c);if(d.length===0)A.success(E.default.green("Hook scripts: PASS")+E.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let h of d){let g=ue(c,h);try{rT(g,nT.R_OK),A.success(E.default.green("Hook script exists: PASS")+E.default.dim(` \u2014 ${g}`))}catch{A.error(E.default.red("Hook script exists: FAIL")+E.default.dim(` \u2014 not found at ${g}`))}}A.step(`Checking ${e.name} plugin registration...`);let l=e.checkPluginRegistration();l.status==="pass"?A.success(E.default.green("Plugin enabled: PASS")+E.default.dim(` \u2014 ${l.message}`)):A.warn(E.default.yellow("Plugin enabled: WARN")+` \u2014 ${l.message}`),A.step("Checking FTS5 / SQLite...");try{let h=(await Promise.resolve().then(()=>(fs(),SE))).loadDatabase(),g=new h(":memory:");g.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),g.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let _=g.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();g.close(),_&&_.content==="hello world"?A.success(E.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,A.error(E.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(h){let g=h instanceof Error?h.message:String(h),_=_s(),v=ue(_,"node_modules","better-sqlite3");!Fe(v)?(r++,A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+E.default.dim(" \u2014 package-missing")+E.default.dim(`
1010
1010
  Path: ${v}
1011
1011
  Root cause: npm silently skipped better-sqlite3 because the package's \`engines\` field excluded the running Node (issue #514, e.g. Node 26 vs better-sqlite3@12.x).
1012
1012
  Try (primary): cd "${_}" && npm install better-sqlite3 --no-optional
@@ -1014,19 +1014,19 @@ Could not auto-open browser. Open manually: ${t}`),o=A2(t,e),i=!1;for(let{cmd:a,
1014
1014
  Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
1015
1015
  Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
1016
1016
  Try (fallback): npm rebuild better-sqlite3`)):A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+E.default.dim(`
1017
- Try: npm rebuild better-sqlite3`)))}A.step("Checking versions...");let p=nT(),f=await F2(),m=e.getInstalledVersion();return f==="unknown"?A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, could not reach npm registry`):p===f?A.success(E.default.green("npm (MCP): PASS")+` \u2014 v${p}`):A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, latest v${f}`+E.default.dim(`
1017
+ Try: npm rebuild better-sqlite3`)))}A.step("Checking versions...");let p=sT(),f=await V2(),m=e.getInstalledVersion();return f==="unknown"?A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, could not reach npm registry`):p===f?A.success(E.default.green("npm (MCP): PASS")+` \u2014 v${p}`):A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, latest v${f}`+E.default.dim(`
1018
1018
  Run: /context-mode:ctx-upgrade`)),m==="not installed"?A.info(E.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):f!=="unknown"&&m===f?A.success(E.default.green(`${e.name}: PASS`)+` \u2014 v${m}`):f!=="unknown"?A.warn(E.default.yellow(`${e.name}: WARN`)+` \u2014 v${m}, latest v${f}`+E.default.dim(`
1019
- Run: /context-mode:ctx-upgrade`)):A.info(`${e.name}: v${m}`+E.default.dim(" \u2014 could not verify against npm registry")),r>0?(ha(E.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(ha(o.length>=4?E.default.green("Diagnostics complete!"):E.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function H2(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:s,cpSync:o}=await import("node:fs"),i=ue(ys(),"insight"),a=sr(),u=(await jo(a.platform)).getSessionDir(),d=gt(zy(u),"content"),l=gt(zy(u),"insight-cache");Fe(gt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),s(l,{recursive:!0});let p=n(gt(i,"server.mjs")).mtimeMs,f=Fe(gt(l,"server.mjs"))?n(gt(l,"server.mjs")).mtimeMs:0;if(p>f&&(console.log("Copying Insight source..."),o(i,l,{recursive:!0,force:!0})),!Fe(gt(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{M2("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{To(gt(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!Fe(gt(l,"node_modules","vite"))||!Fe(gt(l,"node_modules","better-sqlite3")))throw To(gt(l,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:l,stdio:"pipe",timeout:6e4});let m=`http://localhost:${t}`;console.log(`
1019
+ Run: /context-mode:ctx-upgrade`)):A.info(`${e.name}: v${m}`+E.default.dim(" \u2014 could not verify against npm registry")),r>0?(ga(E.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(ga(o.length>=4?E.default.green("Diagnostics complete!"):E.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function G2(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:s,cpSync:o}=await import("node:fs"),i=ue(_s(),"insight"),a=sr(),u=(await zo(a.platform)).getSessionDir(),d=gt(Fy(u),"content"),l=gt(Fy(u),"insight-cache");Fe(gt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),s(l,{recursive:!0});let p=n(gt(i,"server.mjs")).mtimeMs,f=Fe(gt(l,"server.mjs"))?n(gt(l,"server.mjs")).mtimeMs:0;if(p>f&&(console.log("Copying Insight source..."),o(i,l,{recursive:!0,force:!0})),!Fe(gt(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{H2("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{To(gt(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!Fe(gt(l,"node_modules","vite"))||!Fe(gt(l,"node_modules","better-sqlite3")))throw To(gt(l,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:l,stdio:"pipe",timeout:6e4});let m=`http://localhost:${t}`;console.log(`
1020
1020
  context-mode Insight
1021
1021
  ${m}
1022
1022
  `);let h=r("node",[gt(l,"server.mjs")],{cwd:l,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:d},stdio:"inherit"});h.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((_,v)=>{let y=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},x=>{_(),x.resume()});y.on("error",v),y.on("timeout",()=>{y.destroy(),v(new Error("timeout"))}),y.end()})}catch{console.error(`
1023
1023
  Error: Port ${t} appears to be in use. Either a previous dashboard is still running, or another service is using this port.`),console.error(`
1024
- To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}j2(m),process.on("SIGINT",()=>{h.kill(),process.exit(0)}),process.on("SIGTERM",()=>{h.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
1025
- Insight error: ${r}`),process.exit(1)}}async function Z2(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:sr(),r=await jo(e.platform);$l(E.default.bgCyan(E.default.black(" context-mode upgrade "))),A.info(`Platform: ${E.default.cyan(r.name)}`+E.default.dim(` (${e.confidence} confidence)`));let n=ys(),s=[],o=Pl(),i=ue(Ze(),"plugins","marketplaces","context-mode");if(Fe(gt(i,".git"))){o.start("Syncing marketplace clone");try{$o("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(o.stop(E.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),A.info(E.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):($o("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),$o("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),o.stop(E.default.green("Marketplace clone synced")),s.push("Marketplace clone updated to upstream"))}catch(p){let f=p instanceof Error?p.message:String(p);o.stop(E.default.yellow("Marketplace sync skipped")),A.warn(E.default.yellow("git refresh on marketplace failed")+` \u2014 ${f}`),A.info(E.default.dim(" Continuing \u2014 cache dir update will still happen."))}}A.step("Pulling latest from GitHub...");let a=nT(),c=gt(C2(),`context-mode-upgrade-${Date.now()}`);o.start("Cloning mksglu/context-mode");try{$o("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),o.stop("Downloaded");let p=c,m=JSON.parse(Wr(ue(p,"package.json"),"utf-8")).version??"unknown";if(m===a)A.success(E.default.green("Already on latest")+` \u2014 v${a}`),To(c,{recursive:!0,force:!0});else{A.info(`Update available: ${E.default.yellow("v"+a)} \u2192 ${E.default.green("v"+m)}`),o.start("Installing dependencies & building"),ll(["install","--no-audit","--no-fund"],{cwd:p,stdio:"pipe",timeout:12e4}),ll(["run","build"],{cwd:p,stdio:"pipe",timeout:6e4}),o.stop("Built successfully"),o.start("Updating files in-place");let g=[...JSON.parse(Wr(ue(p,"package.json"),"utf-8")).files||[],"src","package.json"];for(let x of g)try{To(ue(n,x),{recursive:!0,force:!0}),Q$(ue(p,x),ue(n,x),{recursive:!0})}catch{}let _={mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}};E2(ue(n,".mcp.json"),JSON.stringify(_,null,2)+`
1026
- `);try{(await Promise.resolve().then(()=>(X$(),Y$))).normalizeHooksOnStartup({pluginRoot:n,nodePath:process.execPath,platform:process.platform})}catch{}o.stop(E.default.green(`Updated in-place to v${m}`));let v=ue(n,".claude-plugin","plugin.json"),y=null;try{let x=JSON.parse(Wr(v,"utf-8"));x&&typeof x.version=="string"&&(y=x.version)}catch{}if(y!==m)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${y??"<missing>"}" but newVersion is "${m}". Refusing to bump registry.`);r.updatePluginRegistry(n,m),A.info(E.default.dim(" Registry synced to "+n));try{let x=ue(Ze(),"plugins","installed_plugins.json");if(Fe(x)){let R=JSON.parse(Wr(x,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(R))for(let $ of R){let P=$?.installPath;if(typeof P!="string"||!P)continue;if(!Fe(P))throw new Error(`installPath does not exist on disk: ${P}`);let j=ue(P,".claude-plugin","plugin.json");if(!Fe(j))throw new Error(`missing plugin.json manifest at ${j}`);let T=JSON.parse(Wr(j,"utf-8"));if(T?.version!==$.version)throw new Error(`version mismatch \u2014 registry says "${$.version}" but ${j} says "${T?.version}"`)}}}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`Registry consistency check failed: ${k}`)}try{let x=ue(Ze(),"plugins","cache"),k="context-mode@context-mode",R=Dl({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if(R&&R.error)throw new Error(R.error);let $=Dl({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if($&&Array.isArray($.healed)&&$.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${$.healed.join(",")})`)}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`plugin.json drift check failed: ${k}`)}try{let x=ue(Ze(),"plugins","cache"),k="context-mode@context-mode",R=Ml({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if(R&&R.error)throw new Error(R.error);let $=Ml({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if($&&Array.isArray($.healed)&&$.healed.length>0)throw new Error(`.mcp.json drift: mcpServers.args still poisoned after first heal pass (healed=${$.healed.join(",")})`)}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`.mcp.json drift check failed: ${k}`)}try{let x=ue(i,".claude-plugin","plugin.json");if(Fe(x)){let k=JSON.parse(Wr(x,"utf-8"));k?.version!==m&&(A.warn(E.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${k?.version}" but expected "${m}"`),A.info(E.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(o.start("Installing production dependencies"),ll(["install","--production","--no-audit","--no-fund"],{cwd:n,stdio:"pipe",timeout:6e4}),o.stop("Dependencies ready"),e.platform!=="opencode"&&e.platform!=="kilo"){o.start("Verifying native addon ABI");let x=ue(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let R=ue(n,"hooks","ensure-deps.mjs");if(!Fe(R))throw new Error(`missing ${R}`);await import(`${dl(R).href}?upgrade=${Date.now()}`),Fe(x)?(o.stop(E.default.green("Native addons OK")+E.default.dim(" \u2014 ABI cache present")),s.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(o.stop(E.default.yellow("Native addon ABI cache missing")),A.warn(E.default.dim(` Try manually: cd "${n}" && npm rebuild better-sqlite3`)))}catch(R){let $=R instanceof Error?R.message:String(R);o.stop(E.default.yellow("Native addon ABI bootstrap unavailable")),A.warn(E.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${$}`+E.default.dim(`
1027
- Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let k=ue(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Fe(k))try{let R=ue(n,"scripts","heal-better-sqlite3.mjs");if(Fe(R)){let $=await import(`${dl(R).href}?upgrade=${Date.now()}`);typeof $.healBetterSqlite3Binding=="function"&&$.healBetterSqlite3Binding(n)}}catch{}Fe(k)||(process.exitCode=1,A.error(E.default.red("better-sqlite3 native binding: MISSING")+E.default.dim(`
1024
+ To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}Z2(m),process.on("SIGINT",()=>{h.kill(),process.exit(0)}),process.on("SIGTERM",()=>{h.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
1025
+ Insight error: ${r}`),process.exit(1)}}async function K2(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:sr(),r=await zo(e.platform);Tl(E.default.bgCyan(E.default.black(" context-mode upgrade "))),A.info(`Platform: ${E.default.cyan(r.name)}`+E.default.dim(` (${e.confidence} confidence)`));let n=_s(),s=[],o=Rl(),i=ue(Ze(),"plugins","marketplaces","context-mode");if(Fe(gt(i,".git"))){o.start("Syncing marketplace clone");try{$o("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(o.stop(E.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),A.info(E.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):($o("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),$o("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),o.stop(E.default.green("Marketplace clone synced")),s.push("Marketplace clone updated to upstream"))}catch(p){let f=p instanceof Error?p.message:String(p);o.stop(E.default.yellow("Marketplace sync skipped")),A.warn(E.default.yellow("git refresh on marketplace failed")+` \u2014 ${f}`),A.info(E.default.dim(" Continuing \u2014 cache dir update will still happen."))}}A.step("Pulling latest from GitHub...");let a=sT(),c=gt(M2(),`context-mode-upgrade-${Date.now()}`);o.start("Cloning mksglu/context-mode");try{$o("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),o.stop("Downloaded");let p=c,m=JSON.parse(Wr(ue(p,"package.json"),"utf-8")).version??"unknown";if(m===a)A.success(E.default.green("Already on latest")+` \u2014 v${a}`),To(c,{recursive:!0,force:!0});else{A.info(`Update available: ${E.default.yellow("v"+a)} \u2192 ${E.default.green("v"+m)}`),o.start("Installing dependencies & building"),dl(["install","--no-audit","--no-fund"],{cwd:p,stdio:"pipe",timeout:12e4}),dl(["run","build"],{cwd:p,stdio:"pipe",timeout:6e4}),o.stop("Built successfully"),o.start("Updating files in-place");let g=[...JSON.parse(Wr(ue(p,"package.json"),"utf-8")).files||[],"src","package.json"];for(let x of g)try{To(ue(n,x),{recursive:!0,force:!0}),eT(ue(p,x),ue(n,x),{recursive:!0})}catch{}let _={mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}};O2(ue(n,".mcp.json"),JSON.stringify(_,null,2)+`
1026
+ `);try{(await Promise.resolve().then(()=>(Q$(),X$))).normalizeHooksOnStartup({pluginRoot:n,nodePath:process.execPath,platform:process.platform})}catch{}o.stop(E.default.green(`Updated in-place to v${m}`));let v=ue(n,".claude-plugin","plugin.json"),y=null;try{let x=JSON.parse(Wr(v,"utf-8"));x&&typeof x.version=="string"&&(y=x.version)}catch{}if(y!==m)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${y??"<missing>"}" but newVersion is "${m}". Refusing to bump registry.`);r.updatePluginRegistry(n,m),A.info(E.default.dim(" Registry synced to "+n));try{let x=ue(Ze(),"plugins","installed_plugins.json");if(Fe(x)){let R=JSON.parse(Wr(x,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(R))for(let $ of R){let P=$?.installPath;if(typeof P!="string"||!P)continue;if(!Fe(P))throw new Error(`installPath does not exist on disk: ${P}`);let j=ue(P,".claude-plugin","plugin.json");if(!Fe(j))throw new Error(`missing plugin.json manifest at ${j}`);let T=JSON.parse(Wr(j,"utf-8"));if(T?.version!==$.version)throw new Error(`version mismatch \u2014 registry says "${$.version}" but ${j} says "${T?.version}"`)}}}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`Registry consistency check failed: ${k}`)}try{let x=ue(Ze(),"plugins","cache"),k="context-mode@context-mode",R=Ml({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if(R&&R.error)throw new Error(R.error);let $=Ml({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if($&&Array.isArray($.healed)&&$.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${$.healed.join(",")})`)}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`plugin.json drift check failed: ${k}`)}try{let x=ue(Ze(),"plugins","cache"),k="context-mode@context-mode",R=jl({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if(R&&R.error)throw new Error(R.error);let $=jl({pluginRoot:n,pluginCacheRoot:x,pluginKey:k});if($&&Array.isArray($.healed)&&$.healed.length>0)throw new Error(`.mcp.json drift: mcpServers.args still poisoned after first heal pass (healed=${$.healed.join(",")})`)}catch(x){let k=x instanceof Error?x.message:String(x);throw new Error(`.mcp.json drift check failed: ${k}`)}try{let x=ue(i,".claude-plugin","plugin.json");if(Fe(x)){let k=JSON.parse(Wr(x,"utf-8"));k?.version!==m&&(A.warn(E.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${k?.version}" but expected "${m}"`),A.info(E.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(o.start("Installing production dependencies"),dl(["install","--production","--no-audit","--no-fund"],{cwd:n,stdio:"pipe",timeout:6e4}),o.stop("Dependencies ready"),e.platform!=="opencode"&&e.platform!=="kilo"){o.start("Verifying native addon ABI");let x=ue(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let R=ue(n,"hooks","ensure-deps.mjs");if(!Fe(R))throw new Error(`missing ${R}`);await import(`${pl(R).href}?upgrade=${Date.now()}`),Fe(x)?(o.stop(E.default.green("Native addons OK")+E.default.dim(" \u2014 ABI cache present")),s.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(o.stop(E.default.yellow("Native addon ABI cache missing")),A.warn(E.default.dim(` Try manually: cd "${n}" && npm rebuild better-sqlite3`)))}catch(R){let $=R instanceof Error?R.message:String(R);o.stop(E.default.yellow("Native addon ABI bootstrap unavailable")),A.warn(E.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${$}`+E.default.dim(`
1027
+ Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let k=ue(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Fe(k))try{let R=ue(n,"scripts","heal-better-sqlite3.mjs");if(Fe(R)){let $=await import(`${pl(R).href}?upgrade=${Date.now()}`);typeof $.healBetterSqlite3Binding=="function"&&$.healBetterSqlite3Binding(n)}}catch{}Fe(k)||(process.exitCode=1,A.error(E.default.red("better-sqlite3 native binding: MISSING")+E.default.dim(`
1028
1028
  Path: ${k}`)+E.default.dim(`
1029
1029
  Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+E.default.dim(`
1030
1030
  Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+E.default.dim(`
1031
- Try (fallback): /context-mode:ctx-doctor`)))}o.start("Updating npm global package");try{ll(["install","-g",n,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),o.stop(E.default.green("npm global updated")),s.push("Updated npm global package")}catch{o.stop(E.default.yellow("npm global update skipped")),A.info(E.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}To(c,{recursive:!0,force:!0});try{let x=ue(Ze(),"plugins","installed_plugins.json");if(Fe(x)){let R=JSON.parse(Wr(x,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(R))for(let $ of R){let P=$.installPath;if(P&&P!==n&&Fe(P)){let j=ue(p,"skills");Fe(j)&&(Q$(j,ue(P,"skills"),{recursive:!0}),s.push("Synced skills to active install path"))}}}}catch{}s.push(`Updated v${a} \u2192 v${m}`),A.success(E.default.green("Plugin reinstalled from GitHub!")+E.default.dim(` \u2014 v${m}`))}}catch(p){let f=p instanceof Error?p.message:String(p);o.stop(E.default.red("Update failed")),A.error(E.default.red("GitHub pull failed")+` \u2014 ${f}`),A.info(E.default.dim("Continuing with hooks/settings fix..."));try{To(c,{recursive:!0,force:!0})}catch{}}A.step(`Backing up ${r.name} settings...`);let u=r.backupSettings();u?.endsWith(".bak")?(A.success(E.default.green("Backup created")+E.default.dim(" -> "+u)),s.push("Backed up settings")):u?A.success(E.default.green("Backup skipped")+E.default.dim(" \u2014 no changes needed")):A.warn(E.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),A.step(`Configuring ${r.name} hooks...`);try{let p=r.configureAllHooks(n);for(let f of p)A.info(E.default.dim(` ${f}`)),s.push(f);A.success(E.default.green("Hooks configured")+E.default.dim(` \u2014 ${r.name}`))}catch(p){let f=p instanceof Error?p.message:String(p);throw new Error(`Hook configuration failed: ${f}`)}A.step("Setting hook script permissions...");let d=r.setHookPermissions(n);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let f=ue(n,p);try{tT(f,rT.F_OK),P2(f,493),d.push(f)}catch{}}d.length>0?(A.success(E.default.green("Permissions set")+E.default.dim(` \u2014 ${d.length} hook script(s)`)),s.push(`Set ${d.length} hook scripts as executable`)):A.error(E.default.red("No hook scripts found")+E.default.dim(" \u2014 expected in "+ue(n,"hooks"))),s.length>0?Tl(s.map(p=>E.default.green(" + ")+p).join(`
1032
- `),"Changes Applied"):A.info(E.default.dim("No changes were needed."));let l=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";A.warn(E.default.yellow("Restart for new MCP tools to take effect.")+E.default.dim(` (${l})`)),A.step("Running doctor to verify..."),console.log();try{let p=ue(n,"cli.bundle.mjs"),f=ue(n,"build","cli.js"),m=Fe(p)?p:f;$o("node",[m,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n})}catch{A.warn(E.default.yellow("Doctor had warnings")+E.default.dim(` \u2014 restart your ${r.name} session to pick up the new version`))}}function B2(){let t=Ze(),e=[ue(ys(),"bin","statusline.mjs"),ue(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=ue(t,"plugins","installed_plugins.json");if(Fe(n)){let o=JSON.parse(Wr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(o))for(let i of o){let a=i?.installPath;typeof a=="string"&&a&&e.push(ue(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>Fe(n));r||process.exit(0),import(dl(r).href).catch(()=>{process.exit(0)})}export{M2 as npmExec,ll as npmExecFile,j2 as openInBrowser,oG as toUnixPath};
1031
+ Try (fallback): /context-mode:ctx-doctor`)))}o.start("Updating npm global package");try{dl(["install","-g",n,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),o.stop(E.default.green("npm global updated")),s.push("Updated npm global package")}catch{o.stop(E.default.yellow("npm global update skipped")),A.info(E.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}To(c,{recursive:!0,force:!0});try{let x=ue(Ze(),"plugins","installed_plugins.json");if(Fe(x)){let R=JSON.parse(Wr(x,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(R))for(let $ of R){let P=$.installPath;if(P&&P!==n&&Fe(P)){let j=ue(p,"skills");Fe(j)&&(eT(j,ue(P,"skills"),{recursive:!0}),s.push("Synced skills to active install path"))}}}}catch{}s.push(`Updated v${a} \u2192 v${m}`),A.success(E.default.green("Plugin reinstalled from GitHub!")+E.default.dim(` \u2014 v${m}`))}}catch(p){let f=p instanceof Error?p.message:String(p);o.stop(E.default.red("Update failed")),A.error(E.default.red("GitHub pull failed")+` \u2014 ${f}`),A.info(E.default.dim("Continuing with hooks/settings fix..."));try{To(c,{recursive:!0,force:!0})}catch{}}A.step(`Backing up ${r.name} settings...`);let u=r.backupSettings();u?.endsWith(".bak")?(A.success(E.default.green("Backup created")+E.default.dim(" -> "+u)),s.push("Backed up settings")):u?A.success(E.default.green("Backup skipped")+E.default.dim(" \u2014 no changes needed")):A.warn(E.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),A.step(`Configuring ${r.name} hooks...`);try{let p=r.configureAllHooks(n);for(let f of p)A.info(E.default.dim(` ${f}`)),s.push(f);A.success(E.default.green("Hooks configured")+E.default.dim(` \u2014 ${r.name}`))}catch(p){let f=p instanceof Error?p.message:String(p);throw new Error(`Hook configuration failed: ${f}`)}A.step("Setting hook script permissions...");let d=r.setHookPermissions(n);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let f=ue(n,p);try{rT(f,nT.F_OK),N2(f,493),d.push(f)}catch{}}d.length>0?(A.success(E.default.green("Permissions set")+E.default.dim(` \u2014 ${d.length} hook script(s)`)),s.push(`Set ${d.length} hook scripts as executable`)):A.error(E.default.red("No hook scripts found")+E.default.dim(" \u2014 expected in "+ue(n,"hooks"))),s.length>0?Pl(s.map(p=>E.default.green(" + ")+p).join(`
1032
+ `),"Changes Applied"):A.info(E.default.dim("No changes were needed."));let l=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";A.warn(E.default.yellow("Restart for new MCP tools to take effect.")+E.default.dim(` (${l})`)),A.step("Running doctor to verify..."),console.log();try{let p=ue(n,"cli.bundle.mjs"),f=ue(n,"build","cli.js"),m=Fe(p)?p:f;$o("node",[m,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n})}catch{A.warn(E.default.yellow("Doctor had warnings")+E.default.dim(` \u2014 restart your ${r.name} session to pick up the new version`))}}function J2(){let t=Ze(),e=[ue(_s(),"bin","statusline.mjs"),ue(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=ue(t,"plugins","installed_plugins.json");if(Fe(n)){let o=JSON.parse(Wr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(o))for(let i of o){let a=i?.installPath;typeof a=="string"&&a&&e.push(ue(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>Fe(n));r||process.exit(0),import(pl(r).href).catch(()=>{process.exit(0)})}export{H2 as npmExec,dl as npmExecFile,Z2 as openInBrowser,pG as toUnixPath};